public function EntityNG::getTranslation

Implements \Drupal\Core\TypedData\TranslatableInterface::getTranslation().

Return value

\Drupal\Core\Entity\Field\Type\EntityTranslation

Overrides Entity::getTranslation

File

drupal/core/lib/Drupal/Core/Entity/EntityNG.php, line 351
Contains \Drupal\Core\Entity\EntityNG.

Class

EntityNG
Implements Entity Field API specific enhancements to the Entity class.

Namespace

Drupal\Core\Entity

Code

public function getTranslation($langcode, $strict = TRUE) {

  // If the default language is Language::LANGCODE_NOT_SPECIFIED, the entity is not
  // translatable, so we use Language::LANGCODE_DEFAULT.
  if ($langcode == Language::LANGCODE_DEFAULT || in_array($this
    ->language()->langcode, array(
    Language::LANGCODE_NOT_SPECIFIED,
    $langcode,
  ))) {

    // No translation needed, return the entity.
    return $this;
  }

  // Check whether the language code is valid, thus is of an available
  // language.
  $languages = language_list(Language::STATE_ALL);
  if (!isset($languages[$langcode])) {
    throw new InvalidArgumentException("Unable to get translation for the invalid language '{$langcode}'.");
  }
  $fields = array();
  foreach ($this
    ->getPropertyDefinitions() as $name => $definition) {

    // Load only translatable properties in strict mode.
    if (!empty($definition['translatable']) || !$strict) {
      $fields[$name] = $this
        ->getTranslatedField($name, $langcode);
    }
  }

  // @todo: Add a way to get the definition of a translation to the
  // TranslatableInterface and leverage TypeDataManager::getPropertyInstance
  // also.
  $translation_definition = array(
    'type' => 'entity_translation',
    'constraints' => array(
      'entity type' => $this
        ->entityType(),
      'bundle' => $this
        ->bundle(),
    ),
  );
  $translation = \Drupal::typedData()
    ->create($translation_definition, $fields);
  $translation
    ->setStrictMode($strict);
  $translation
    ->setContext('@' . $langcode, $this);
  return $translation;
}