function LinkCollectionNormalizer::normalize

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

File

core/modules/jsonapi/src/Normalizer/LinkCollectionNormalizer.php, line 93

Class

LinkCollectionNormalizer
Normalizes a LinkCollection object.

Namespace

Drupal\jsonapi\Normalizer

Code

public function normalize($object, $format = NULL, array $context = []) {
    assert($object instanceof LinkCollection);
    $normalized = [];
    
    /** @var \Drupal\jsonapi\JsonApiResource\Link $link */
    foreach ($object as $key => $links) {
        $is_multiple = count($links) > 1;
        foreach ($links as $link) {
            $link_key = $is_multiple ? sprintf('%s--%s', $key, $this->hashByHref($link)) : $key;
            $attributes = $link->getTargetAttributes();
            $normalization = array_merge([
                'href' => $link->getHref(),
            ], !empty($attributes) ? [
                'meta' => $attributes,
            ] : []);
            // Checking access on links is not about access to the link itself;
            // it is about whether the current user has access to the route that is
            // *targeted* by the link. This is done on a "best effort" basis. That
            // is, some links target routes that depend on a request to determine if
            // they're accessible or not. Some other links might target routes to
            // which the current user will clearly not have access, in that case
            // this code proactively removes those links from the response.
            $access = $link->getUri()
                ->access($this->currentUser, TRUE);
            $cacheability = CacheableMetadata::createFromObject($link)->addCacheableDependency($access);
            $normalized[$link_key] = $access->isAllowed() ? new CacheableNormalization($cacheability, $normalization) : new CacheableOmission($cacheability);
        }
    }
    return CacheableNormalization::aggregate($normalized);
}

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