You are here

public function EntityNormalizer::normalize in JSON:API 8

File

src/Normalizer/EntityNormalizer.php, line 85

Class

EntityNormalizer
Converts the Drupal entity object to a JSON API array structure.

Namespace

Drupal\jsonapi\Normalizer

Code

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

  // If the fields to use were specified, only output those field values.
  $context['resource_type'] = $resource_type = $this->resourceTypeRepository
    ->get($entity
    ->getEntityTypeId(), $entity
    ->bundle());
  $resource_type_name = $resource_type
    ->getTypeName();

  // 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.
  $bundle = $resource_type
    ->getBundle();
  if (!empty($context['sparse_fieldset'][$resource_type_name])) {
    $field_names = $context['sparse_fieldset'][$resource_type_name];
  }
  else {
    $field_names = $this
      ->getFieldNames($entity, $bundle, $resource_type);
  }

  /* @var Value\FieldNormalizerValueInterface[] $normalizer_values */
  $normalizer_values = [];
  $relationship_field_names = array_keys($resource_type
    ->getRelatableResourceTypes());
  foreach ($this
    ->getFields($entity, $bundle, $resource_type) as $field_name => $field) {
    $normalized_field = $this
      ->serializeField($field, $context, $format);
    assert($normalized_field instanceof FieldNormalizerValueInterface);
    $in_sparse_fieldset = in_array($field_name, $field_names);
    $is_relationship_field = in_array($field_name, $relationship_field_names);

    // Omit fields not listed in sparse fieldsets, except if they're fields
    // modeling relationships; despite a relationship field being omitted,
    // using `?include` to include related resources is still allowed.
    if (!$in_sparse_fieldset) {
      if ($is_relationship_field) {
        $is_null_field = $field instanceof NullFieldNormalizerValue;
        $has_includes = !empty($normalized_field
          ->getIncludes());
        if (!$is_null_field && $has_includes) {
          $normalizer_values[$field_name] = new IncludeOnlyRelationshipNormalizerValue($normalized_field);
        }
      }
      continue;
    }
    $normalizer_values[$field_name] = $normalized_field;
  }
  $link_context = [
    'link_manager' => $this->linkManager,
  ];
  return new EntityNormalizerValue($normalizer_values, $context, $entity, $link_context);
}