function EntityReferenceFieldNormalizer::normalize

Same name in other branches
  1. 9 core/modules/jsonapi/src/Normalizer/EntityReferenceFieldNormalizer.php \Drupal\jsonapi\Normalizer\EntityReferenceFieldNormalizer::normalize()
  2. 8.9.x core/modules/jsonapi/src/Normalizer/EntityReferenceFieldNormalizer.php \Drupal\jsonapi\Normalizer\EntityReferenceFieldNormalizer::normalize()
  3. 10 core/modules/jsonapi/src/Normalizer/EntityReferenceFieldNormalizer.php \Drupal\jsonapi\Normalizer\EntityReferenceFieldNormalizer::normalize()

Overrides FieldNormalizer::normalize

File

core/modules/jsonapi/src/Normalizer/EntityReferenceFieldNormalizer.php, line 30

Class

EntityReferenceFieldNormalizer
Normalizer class specific for entity reference field objects.

Namespace

Drupal\jsonapi\Normalizer

Code

public function normalize($field, $format = NULL, array $context = []) : array|string|int|float|bool|\ArrayObject|null {
    assert($field instanceof EntityReferenceFieldItemListInterface);
    // Build the relationship object based on the Entity Reference and normalize
    // that object instead.
    $resource_identifiers = array_filter(ResourceIdentifier::toResourceIdentifiers($field->filterEmptyItems()), function (ResourceIdentifierInterface $resource_identifier) {
        return !$resource_identifier->getResourceType()
            ->isInternal();
    });
    $normalized_items = CacheableNormalization::aggregate($this->serializer
        ->normalize($resource_identifiers, $format, $context));
    assert($context['resource_object'] instanceof ResourceObject);
    $resource_relationship = $context['resource_object']->getResourceType()
        ->getFieldByInternalName($field->getName());
    assert($resource_relationship instanceof ResourceTypeRelationship);
    $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'], $resource_relationship));
    $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' => $resource_relationship->hasOne() ? array_shift($data_normalization) : $data_normalization,
    ];
    if (!empty($links)) {
        $normalization['links'] = $links;
    }
    return (new CacheableNormalization($normalized_items, $normalization))->withCacheableDependency($link_cacheability);
}

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