You are here

public function ResourceIdentifierNormalizer::normalize in JSON:API Extras 8.3

Overrides JsonApiNormalizerDecoratorBase::normalize

File

src/Normalizer/ResourceIdentifierNormalizer.php, line 44

Class

ResourceIdentifierNormalizer
Converts the Drupal entity reference item object to a JSON:API structure.

Namespace

Drupal\jsonapi_extras\Normalizer

Code

public function normalize($field, $format = NULL, array $context = []) {
  assert($field instanceof ResourceIdentifier);
  $normalized_output = parent::normalize($field, $format, $context);
  assert($normalized_output instanceof CacheableNormalization);
  if (!isset($context['resource_object'])) {
    return $normalized_output;
  }
  $resource_object = $context['resource_object'];

  // Find the name of the field being normalized. This is unreasonably more
  // contrived than one could expect for ResourceIdentifiers.
  $resource_type = $resource_object
    ->getResourceType();
  $field_name = $this
    ->guessFieldName($field
    ->getId(), $resource_object);
  if (!$field_name) {
    return $normalized_output;
  }
  $enhancer = $resource_type
    ->getFieldEnhancer($field_name);
  if (!$enhancer) {
    return $normalized_output;
  }

  // Apply any enhancements necessary.
  $context['field_resource_identifier'] = $field;
  $transformed = $enhancer
    ->undoTransform($normalized_output
    ->getNormalization(), new Context($context));

  // @todo Enhancers should utilize CacheableNormalization to infer additional cacheability from the enhancer.
  return new CacheableNormalization($normalized_output, array_intersect_key($transformed, array_flip([
    'id',
    'type',
    'meta',
  ])));
}