You are here

public function LinkCollectionNormalizer::normalize in Drupal 8

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

File

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

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,
      ] : []);
      $normalized[$link_key] = new CacheableNormalization($link, $normalization);
    }
  }
  return CacheableNormalization::aggregate($normalized);
}