Language.php 2.04 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\TypedData\Plugin\DataType\Language.
6 7
 */

8
namespace Drupal\Core\TypedData\Plugin\DataType;
9

10
use Drupal\Core\TypedData\TypedData;
11 12 13 14 15

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

  /**
28
   * The id of the language.
29 30 31
   *
   * @var string
   */
32 33 34 35 36 37
  protected $id;

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

  /**
40
   * Overrides TypedData::getValue().
41
   *
42
   * @return \Drupal\Core\Language\LanguageInterface|null
43 44
   */
  public function getValue() {
45 46
    if (!isset($this->language) && $this->id) {
      $this->language = language_load($this->id);
47
    }
48
    return $this->language;
49 50 51
  }

  /**
52
   * Overrides TypedData::setValue().
53 54 55
   *
   * Both the langcode and the language object may be passed as value.
   */
56
  public function setValue($value, $notify = TRUE) {
57 58
    // Support passing language objects.
    if (is_object($value)) {
59
      $this->id = $value->getId();
60
      $this->language = $value;
61 62
    }
    elseif (isset($value) && !is_scalar($value)) {
63
      throw new \InvalidArgumentException('Value is no valid langcode or language object.');
64 65
    }
    else {
66
      $this->id = $value;
67 68 69 70 71
      $this->language = NULL;
    }
    // Notify the parent of any changes.
    if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
72 73 74 75
    }
  }

  /**
76
   * Overrides TypedData::getString().
77 78 79
   */
  public function getString() {
    $language = $this->getValue();
80
    return $language ? $language->getName() : '';
81
  }
82 83 84 85 86 87 88 89 90

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

95
}