You are here

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

2 methods override DataDefinitionNormalizer::normalize()
ComplexDataDefinitionNormalizer::normalize in src/Normalizer/ComplexDataDefinitionNormalizer.php
ListDataDefinitionNormalizer::normalize in src/Normalizer/ListDataDefinitionNormalizer.php

File

src/Normalizer/DataDefinitionNormalizer.php, line 49

Class

DataDefinitionNormalizer
Normalizer for DataDefinitionInterface instances.

Namespace

Drupal\jsonapi_schema\Normalizer

Code

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

  // `text source` and `date source` produce objects not supported in the API.
  // It is not clear how the API excludes them.
  // @todo properly identify and exclude this class of computed objects.
  if ($entity
    ->getSetting('text source') || $entity
    ->getSetting('date source')) {
    return [];
  }
  $property = $this
    ->extractPropertyData($entity, $context);
  if (!is_object($property) && !empty($context['parent']) && $context['name'] == 'value') {
    if ($maxLength = $context['parent']
      ->getSetting('max_length')) {
      $property['maxLength'] = $maxLength;
    }
    if (empty($context['parent']
      ->getSetting('allowed_values_function')) && !empty($context['parent']
      ->getSetting('allowed_values'))) {
      $allowed_values = $context['parent']
        ->getSetting('allowed_values');
      $property['enum'] = array_keys($allowed_values);
    }
  }
  if (!is_object($property) && !isset($property['title']) && isset($context['name'])) {
    $property['title'] = $context['name'];
  }
  $normalized = [
    'properties' => [],
  ];
  if (!is_object($property) && !in_array($property['type'], static::JSON_TYPES)) {

    // Unable to find the correct type.
    \Drupal::logger('jsonapi_schema')
      ->error('{type} is not a valid type for a JSON document.', [
      'type' => $property['type'],
    ]);
    $property = (object) [];
  }
  $normalized['properties'][$context['name']] = $property;
  if ($this
    ->requiredProperty($entity)) {
    $normalized['required'][] = $context['name'];
  }
  return $normalized;
}