You are here

public function ResourceObjectNormalizer::normalize in Drupal 8

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

File

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

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 = []) {
  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);
}