function ResourceObjectNormalizer::normalize

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

File

core/modules/jsonapi/src/Normalizer/ResourceObjectNormalizer.php, line 52

Class

ResourceObjectNormalizer
Converts the JSON:API module ResourceObject into a JSON:API array structure.

Namespace

Drupal\jsonapi\Normalizer

Code

public function normalize($object, $format = NULL, array $context = []) : array|string|int|float|bool|\ArrayObject|null {
    assert($object instanceof ResourceObject);
    // If the fields to use were specified, only output those field values.
    $context['resource_object'] = $object;
    $resource_type = $object->getResourceType();
    $resource_type_name = $resource_type->getTypeName();
    $fields = $object->getFields();
    // Get the bundle ID of the requested resource. This is used to determine if
    // this is a bundle level resource or an entity level resource.
    if (!empty($context['sparse_fieldset'][$resource_type_name])) {
        $field_names = $context['sparse_fieldset'][$resource_type_name];
    }
    else {
        $field_names = array_keys($fields);
    }
    $normalization_parts = $this->getNormalization($field_names, $object, $format, $context);
    // Keep only the requested fields (the cached normalization gradually grows
    // to the complete set of fields).
    $fields = $normalization_parts[ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_FIELDS];
    $field_normalizations = array_intersect_key($fields, array_flip($field_names));
    $relationship_field_names = array_keys($resource_type->getRelatableResourceTypes());
    $attributes = array_diff_key($field_normalizations, array_flip($relationship_field_names));
    $relationships = array_intersect_key($field_normalizations, array_flip($relationship_field_names));
    $entity_normalization = array_filter($normalization_parts[ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_BASE] + [
        'attributes' => CacheableNormalization::aggregate($attributes)->omitIfEmpty(),
        'relationships' => CacheableNormalization::aggregate($relationships)->omitIfEmpty(),
    ]);
    return CacheableNormalization::aggregate($entity_normalization)->withCacheableDependency($object);
}

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