summaryrefslogtreecommitdiffstats
path: root/core/lib/Drupal/Core/TypedData/Plugin/DataType/Language.php
blob: 9f74c4f4592b572ee7cc7dedbec895778dc2b5ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php

namespace Drupal\Core\TypedData\Plugin\DataType;

use Drupal\Core\TypedData\TypedData;

/**
 * Defines the 'language' data type.
 *
 * The plain value of a language is the language object, i.e. an instance of
 * \Drupal\Core\Language\Language. For setting the value the language object or
 * the language code as string may be passed.
 *
 * @DataType(
 *   id = "language",
 *   label = @Translation("Language"),
 *   description = @Translation("A language object.")
 * )
 */
class Language extends TypedData {

  /**
   * The id of the language.
   *
   * @var string
   */
  protected $id;

  /**
   * @var \Drupal\Core\Language
   */
  protected $language;

  /**
   * Overrides TypedData::getValue().
   *
   * @return \Drupal\Core\Language\LanguageInterface|null
   */
  public function getValue() {
    if (!isset($this->language) && $this->id) {
      $this->language = \Drupal::languageManager()->getLanguage($this->id);
    }
    return $this->language;
  }

  /**
   * Overrides TypedData::setValue().
   *
   * Both the langcode and the language object may be passed as value.
   */
  public function setValue($value, $notify = TRUE) {
    // Support passing language objects.
    if (is_object($value)) {
      $this->id = $value->getId();
      $this->language = $value;
    }
    elseif (isset($value) && !is_scalar($value)) {
      throw new \InvalidArgumentException('Value is no valid langcode or language object.');
    }
    else {
      $this->id = $value;
      $this->language = NULL;
    }
    // Notify the parent of any changes.
    if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getString() {
    $language = $this->getValue();
    return $language ? $language->getName() : '';
  }

  /**
   * {@inheritdoc}
   */
  public function id() {
    if (isset($this->id)) {
      return $this->id;
    }
    elseif (isset($this->language)) {
      return $this->language->getId();
    }
  }

}