You are here

public function EntityReferenceFieldNormalizer::normalize in JSON:API 8.2

Same name and namespace in other branches
  1. 8 src/Normalizer/EntityReferenceFieldNormalizer.php \Drupal\jsonapi\Normalizer\EntityReferenceFieldNormalizer::normalize()

Overrides FieldNormalizer::normalize

File

src/Normalizer/EntityReferenceFieldNormalizer.php, line 34

Class

EntityReferenceFieldNormalizer
Normalizer class specific for entity reference field objects.

Namespace

Drupal\jsonapi\Normalizer

Code

public function normalize($field, $format = NULL, array $context = []) {
  assert($field instanceof EntityReferenceFieldItemListInterface);

  // Build the relationship object based on the Entity Reference and normalize
  // that object instead.
  $definition = $field
    ->getFieldDefinition();
  $cardinality = $definition
    ->getFieldStorageDefinition()
    ->getCardinality();
  $resource_identifiers = array_filter(ResourceIdentifier::toResourceIdentifiers($field
    ->filterEmptyItems()), function (ResourceIdentifierInterface $resource_identifier) {
    return !$resource_identifier
      ->getResourceType()
      ->isInternal();
  });
  $context['field_name'] = $field
    ->getName();
  $normalized_items = CacheableNormalization::aggregate($this->serializer
    ->normalize($resource_identifiers, $format, $context));
  assert($context['resource_object'] instanceof ResourceObject);
  $link_cacheability = new CacheableMetadata();
  $links = array_map(function (Url $link) use ($link_cacheability) {
    $href = $link
      ->setAbsolute()
      ->toString(TRUE);
    $link_cacheability
      ->addCacheableDependency($href);
    return [
      'href' => $href
        ->getGeneratedUrl(),
    ];
  }, static::getRelationshipLinks($context['resource_object'], $field
    ->getName()));
  $data_normalization = $normalized_items
    ->getNormalization();
  $normalization = [
    // Empty 'to-one' relationships must be NULL.
    // Empty 'to-many' relationships must be an empty array.
    // @link http://jsonapi.org/format/#document-resource-object-linkage
    'data' => $cardinality === 1 ? array_shift($data_normalization) : $data_normalization,
  ];
  if (!empty($links)) {
    $normalization['links'] = $links;
  }
  return (new CacheableNormalization($normalized_items, $normalization))
    ->withCacheableDependency($link_cacheability);
}