FieldDefinitionNormalizer.php in JSON:API Schema 8
File
src/Normalizer/FieldDefinitionNormalizer.php
View source
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
class FieldDefinitionNormalizer extends ListDataDefinitionNormalizer {
protected $supportedInterfaceOrClass = FieldDefinitionInterface::class;
public function normalize($field_definition, $format = NULL, array $context = []) {
assert($field_definition instanceof FieldDefinitionInterface);
$cardinality = $field_definition
->getFieldStorageDefinition()
->getCardinality();
$context['cardinality'] = $cardinality;
$normalized = parent::normalize($field_definition, $format, $context);
$default_value = $field_definition
->getDefaultValueLiteral();
$field_name = $context['name'];
if (!empty($default_value)) {
$field_type = $field_definition
->getType();
$default_value = $cardinality == 1 ? reset($default_value) : $default_value;
$default_value = count($default_value) == 1 ? reset($default_value) : $default_value;
$default_value = $field_type == "boolean" ? boolval($default_value) : $default_value;
NestedArray::setValue($normalized, [
'properties',
$field_name,
'default',
], $default_value);
}
if ($cardinality != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED && $cardinality != 1) {
NestedArray::setValue($normalized, [
'properties',
$field_name,
'maxItems',
], $cardinality);
}
return $normalized;
}
}