You are here

public function FieldItemNormalizer::normalize in Drupal 9

Same name in this branch
  1. 9 core/modules/jsonapi/src/Normalizer/FieldItemNormalizer.php \Drupal\jsonapi\Normalizer\FieldItemNormalizer::normalize()
  2. 9 core/modules/hal/src/Normalizer/FieldItemNormalizer.php \Drupal\hal\Normalizer\FieldItemNormalizer::normalize()
Same name and namespace in other branches
  1. 8 core/modules/jsonapi/src/Normalizer/FieldItemNormalizer.php \Drupal\jsonapi\Normalizer\FieldItemNormalizer::normalize()

This normalizer leaves JSON:API normalizer land and enters the land of Drupal core's serialization system. That system was never designed with cacheability in mind, and hence bubbles cacheability out of band. This must catch it, and pass it to the value object that JSON:API uses.

File

core/modules/jsonapi/src/Normalizer/FieldItemNormalizer.php, line 62

Class

FieldItemNormalizer
Converts the Drupal field item object to a JSON:API array structure.

Namespace

Drupal\jsonapi\Normalizer

Code

public function normalize($field_item, $format = NULL, array $context = []) {
  assert($field_item instanceof FieldItemInterface);

  /** @var \Drupal\Core\TypedData\TypedDataInterface $property */
  $values = [];
  $context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY] = new CacheableMetadata();
  if (!empty($field_item
    ->getProperties(TRUE))) {

    // We normalize each individual value, so each can do their own casting,
    // if needed.
    $field_properties = TypedDataInternalPropertiesHelper::getNonInternalProperties($field_item);
    foreach ($field_properties as $property_name => $property) {
      $values[$property_name] = $this->serializer
        ->normalize($property, $format, $context);
    }

    // Flatten if there is only a single property to normalize.
    $flatten = count($field_properties) === 1 && $field_item::mainPropertyName() !== NULL;
    $values = static::rasterizeValueRecursive($flatten ? reset($values) : $values);
  }
  else {
    $values = $field_item
      ->getValue();
  }
  $normalization = new CacheableNormalization($context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY], $values);
  unset($context[CacheableNormalizerInterface::SERIALIZATION_CONTEXT_CACHEABILITY]);
  return $normalization;
}