You are here

public function RelationshipItemNormalizer::normalize in JSON:API 8

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.

Overrides FieldItemNormalizer::normalize

File

src/Normalizer/RelationshipItemNormalizer.php, line 46

Class

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

Namespace

Drupal\jsonapi\Normalizer

Code

public function normalize($relationship_item, $format = NULL, array $context = []) {

  /* @var $relationship_item \Drupal\jsonapi\Normalizer\RelationshipItem */

  // TODO: We are always loading the referenced entity. Even if it is not
  // going to be included. That may be a performance issue. We do it because
  // we need to know the entity type and bundle to load the JSON API resource
  // type for the relationship item. We need a better way of finding about
  // this.
  $target_entity = $relationship_item
    ->getTargetEntity();
  $values = $relationship_item
    ->getValue();
  if (isset($context['langcode'])) {
    $values['lang'] = $context['langcode'];
  }
  $host_field_name = $relationship_item
    ->getParent()
    ->getPropertyName();
  if (!empty($context['include']) && in_array($host_field_name, $context['include']) && $target_entity !== NULL) {
    $context = $this
      ->buildSubContext($context, $target_entity, $host_field_name);
    $entity_and_access = EntityResource::getEntityAndAccess($target_entity);
    $included_normalizer_value = $this->serializer
      ->normalize(new JsonApiDocumentTopLevel($entity_and_access['entity']), $format, $context);
  }
  else {
    $included_normalizer_value = NULL;
  }
  return new RelationshipItemNormalizerValue($values, new CacheableMetadata(), $relationship_item
    ->getTargetResourceType(), $included_normalizer_value);
}