function EntityReferenceItemNormalizer::normalize

Same name in other branches
  1. 9 core/modules/hal/src/Normalizer/EntityReferenceItemNormalizer.php \Drupal\hal\Normalizer\EntityReferenceItemNormalizer::normalize()

Overrides FieldItemNormalizer::normalize

File

core/modules/hal/src/Normalizer/EntityReferenceItemNormalizer.php, line 66

Class

EntityReferenceItemNormalizer
Converts the Drupal entity reference item object to HAL array structure.

Namespace

Drupal\hal\Normalizer

Code

public function normalize($field_item, $format = NULL, array $context = []) {
    // If this is not a fieldable entity, let the parent implementation handle
    // it, only fieldable entities are supported as embedded resources.
    if (!$this->targetEntityIsFieldable($field_item)) {
        return parent::normalize($field_item, $format, $context);
    }
    
    /** @var $field_item \Drupal\Core\Field\FieldItemInterface */
    $target_entity = $field_item->get('entity')
        ->getValue();
    // If the parent entity passed in a langcode, unset it before normalizing
    // the target entity. Otherwise, untranslatable fields of the target entity
    // will include the langcode.
    $langcode = isset($context['langcode']) ? $context['langcode'] : NULL;
    unset($context['langcode']);
    $context['included_fields'] = [
        'uuid',
    ];
    // Normalize the target entity.
    $embedded = $this->serializer
        ->normalize($target_entity, $format, $context);
    // @todo https://www.drupal.org/project/drupal/issues/3110815 $embedded will
    //   be NULL if the target entity does not exist. Use null coalescence
    //   operator to preserve behavior in PHP 7.4.
    $link = $embedded['_links']['self'] ?? NULL;
    // If the field is translatable, add the langcode to the link relation
    // object. This does not indicate the language of the target entity.
    if ($langcode) {
        $embedded['lang'] = $link['lang'] = $langcode;
    }
    // The returned structure will be recursively merged into the normalized
    // entity so that the items are properly added to the _links and _embedded
    // objects.
    $field_name = $field_item->getParent()
        ->getName();
    $entity = $field_item->getEntity();
    $field_uri = $this->linkManager
        ->getRelationUri($entity->getEntityTypeId(), $entity->bundle(), $field_name, $context);
    return [
        '_links' => [
            $field_uri => [
                $link,
            ],
        ],
        '_embedded' => [
            $field_uri => [
                $embedded,
            ],
        ],
    ];
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.