You are here

public function ComplexDataDefinitionNormalizer::normalize in JSON:API Schema 8

Overrides DataDefinitionNormalizer::normalize

File

src/Normalizer/ComplexDataDefinitionNormalizer.php, line 30

Class

ComplexDataDefinitionNormalizer
Normalizer for ComplexDataDefinitionInterface.

Namespace

Drupal\jsonapi_schema\Normalizer

Code

public function normalize($entity, $format = NULL, array $context = []) {
  assert($entity instanceof ComplexDataDefinitionInterface);
  $context['parent'] = $entity;
  $normalized = $this
    ->extractPropertyData($entity);
  $normalized['type'] = 'object';

  // Retrieve 'properties' and possibly 'required' nested arrays.
  $property_definitions = array_filter($entity
    ->getPropertyDefinitions(), function (DataDefinitionInterface $item) {
    return !$item
      ->isInternal();
  });
  $properties = $this
    ->normalizeProperties($property_definitions, $format, $context);
  $normalized = NestedArray::mergeDeep($normalized, $properties);
  if (count($property_definitions) == 1) {

    // If there is only one property, JSON API does not use the complex data.
    return $normalized['properties'][key($property_definitions)];
  }
  return $normalized;
}