You are here

public function EntityReferenceFieldItemNormalizer::normalize in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/serialization/src/Normalizer/EntityReferenceFieldItemNormalizer.php \Drupal\serialization\Normalizer\EntityReferenceFieldItemNormalizer::normalize()

Overrides ComplexDataNormalizer::normalize

File

core/modules/serialization/src/Normalizer/EntityReferenceFieldItemNormalizer.php, line 42

Class

EntityReferenceFieldItemNormalizer
Adds the file URI to embedded file entities.

Namespace

Drupal\serialization\Normalizer

Code

public function normalize($field_item, $format = NULL, array $context = []) {
  $values = parent::normalize($field_item, $format, $context);
  $this
    ->normalizeRootReferenceValue($values, $field_item);

  /** @var \Drupal\Core\Entity\EntityInterface $entity */
  if ($entity = $field_item
    ->get('entity')
    ->getValue()) {
    $values['target_type'] = $entity
      ->getEntityTypeId();

    // Add the target entity UUID to the normalized output values.
    $values['target_uuid'] = $entity
      ->uuid();

    // Add a 'url' value if there is a reference and a canonical URL. Hard
    // code 'canonical' here as config entities override the default $rel
    // parameter value to 'edit-form.
    if ($entity
      ->hasLinkTemplate('canonical') && !$entity
      ->isNew() && ($url = $entity
      ->toUrl('canonical')
      ->toString(TRUE))) {
      $this
        ->addCacheableDependency($context, $url);
      $values['url'] = $url
        ->getGeneratedUrl();
    }
    elseif ($entity
      ->getEntityTypeId() === 'file') {
      $values['url'] = file_create_url($entity
        ->getFileUri());
    }
  }
  return $values;
}