protected function FieldItemNormalizer::createTranslatedInstance

Get a translated version of the field item instance.

To indicate that a field item applies to one translation of an entity and not another, the property path must originate with a translation of the entity. This is the reason for using target_instances, from which the property path can be traversed up to the root.

Parameters

\Drupal\Core\Entity\Field\FieldItemInterface $field_item: The untranslated field item instance.

$langcode: The langcode.

Return value

\Drupal\Core\Entity\Field\FieldItemInterface The translated field item instance.

1 call to FieldItemNormalizer::createTranslatedInstance()

File

drupal/core/modules/hal/lib/Drupal/hal/Normalizer/FieldItemNormalizer.php, line 101
Contains \Drupal\hal\Normalizer\FieldItemNormalizer.

Class

FieldItemNormalizer
Converts the Drupal field item object structure to HAL array structure.

Namespace

Drupal\hal\Normalizer

Code

protected function createTranslatedInstance(FieldItemInterface $field_item, $langcode) {
  $parent = $field_item
    ->getParent();
  $ancestors = array();

  // Remove the untranslated instance from the field's list of items.
  $parent
    ->offsetUnset($field_item
    ->getName());

  // Get the property path.
  while (!method_exists($parent, 'getTranslation')) {
    array_unshift($ancestors, $parent);
    $parent = $parent
      ->getParent();
  }

  // Recreate the property path with translations.
  $translation = $parent
    ->getTranslation($langcode);
  foreach ($ancestors as $ancestor) {
    $ancestor_name = $ancestor
      ->getName();
    $translation = $translation
      ->get($ancestor_name);
  }

  // Create a new instance at the end of the property path and return it.
  $count = $translation
    ->isEmpty() ? 0 : $translation
    ->count();
  return $translation
    ->offsetGet($count);
}