public function FieldDefinitionNormalizer::normalize in Schemata 8
Same name in this branch
- 8 schemata_json_schema/src/Normalizer/jsonapi/FieldDefinitionNormalizer.php \Drupal\schemata_json_schema\Normalizer\jsonapi\FieldDefinitionNormalizer::normalize()
- 8 schemata_json_schema/src/Normalizer/json/FieldDefinitionNormalizer.php \Drupal\schemata_json_schema\Normalizer\json\FieldDefinitionNormalizer::normalize()
Overrides ListDataDefinitionNormalizer::normalize
File
- schemata_json_schema/
src/ Normalizer/ jsonapi/ FieldDefinitionNormalizer.php, line 28
Class
- FieldDefinitionNormalizer
- Normalizer for FieldDefinitionInterface objects.
Namespace
Drupal\schemata_json_schema\Normalizer\jsonapiCode
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);
// Specify non-contextual default value as an example.
$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',
'attributes',
'properties',
$field_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) {
NestedArray::setValue($normalized, [
'properties',
'attributes',
'properties',
$field_name,
'maxItems',
], $cardinality);
}
return $normalized;
}