You are here

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

Overrides ListDataDefinitionNormalizer::normalize

File

src/Normalizer/RelationshipFieldDefinitionNormalizer.php, line 61

Class

RelationshipFieldDefinitionNormalizer
Normalizer for RelationshipFieldDefinitionNormalizer objects.

Namespace

Drupal\jsonapi_schema\Normalizer

Code

public function normalize($entity, $format = NULL, array $context = []) {
  $cardinality = $entity
    ->getFieldStorageDefinition()
    ->getCardinality();
  $context['cardinality'] = $cardinality;
  assert($entity instanceof FieldDefinitionInterface);
  $normalized = [
    'description' => t('Entity relationships'),
    'properties' => [
      $context['name'] => $this
        ->normalizeRelationship($entity, $format, $context),
    ],
    'type' => 'object',
  ];

  // Specify non-contextual default value as an example.
  $default_value = $entity
    ->getDefaultValueLiteral();
  if (!empty($default_value)) {
    $normalized['properties'][$context['name']]['default'] = $default_value;
  }

  // The cardinality is the configured maximum number of values the field can
  // contain. If unlimited, we do not include a maxItems attribute.
  if ($cardinality != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED && $cardinality != 1) {
    $normalized['properties'][$context['name']]['maxItems'] = $cardinality;
  }
  return $normalized;
}