function JsonApiDocumentTopLevelNormalizer::normalize

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

File

core/modules/jsonapi/src/Normalizer/JsonApiDocumentTopLevelNormalizer.php, line 175

Class

JsonApiDocumentTopLevelNormalizer
Normalizes the top-level document according to the JSON:API specification.

Namespace

Drupal\jsonapi\Normalizer

Code

public function normalize($object, $format = NULL, array $context = []) {
    assert($object instanceof JsonApiDocumentTopLevel);
    $data = $object->getData();
    $document['jsonapi'] = CacheableNormalization::permanent([
        'version' => JsonApiSpec::SUPPORTED_SPECIFICATION_VERSION,
        'meta' => [
            'links' => [
                'self' => [
                    'href' => JsonApiSpec::SUPPORTED_SPECIFICATION_PERMALINK,
                ],
            ],
        ],
    ]);
    if ($data instanceof ErrorCollection) {
        $document['errors'] = $this->normalizeErrorDocument($object, $format, $context);
    }
    else {
        // Add data.
        $document['data'] = $this->serializer
            ->normalize($data, $format, $context);
        // Add includes.
        $document['included'] = $this->serializer
            ->normalize($object->getIncludes(), $format, $context)
            ->omitIfEmpty();
        // Add omissions and metadata.
        $normalized_omissions = $this->normalizeOmissionsLinks($object->getOmissions(), $format, $context);
        $meta = !$normalized_omissions instanceof CacheableOmission ? array_merge($object->getMeta(), [
            'omitted' => $normalized_omissions->getNormalization(),
        ]) : $object->getMeta();
        $document['meta'] = (new CacheableNormalization($normalized_omissions, $meta))->omitIfEmpty();
    }
    // Add document links.
    $document['links'] = $this->serializer
        ->normalize($object->getLinks(), $format, $context)
        ->omitIfEmpty();
    // Every JSON:API document contains absolute URLs.
    return CacheableNormalization::aggregate($document)->withCacheableDependency((new CacheableMetadata())->addCacheContexts([
        'url.site',
    ]));
}

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