ListDataDefinitionNormalizer.php in Schemata 8
File
schemata_json_schema/src/Normalizer/jsonapi/ListDataDefinitionNormalizer.php
View source
<?php
namespace Drupal\schemata_json_schema\Normalizer\jsonapi;
use Drupal\Core\TypedData\ComplexDataDefinitionInterface;
use Drupal\Core\TypedData\DataReferenceTargetDefinition;
use Drupal\Core\TypedData\ListDataDefinitionInterface;
class ListDataDefinitionNormalizer extends DataDefinitionNormalizer {
protected $supportedInterfaceOrClass = ListDataDefinitionInterface::class;
public function normalize($list_data_definition, $format = NULL, array $context = []) {
assert($list_data_definition instanceof ListDataDefinitionInterface);
$context['parent'] = $list_data_definition;
$property = $this
->extractPropertyData($list_data_definition, $context);
$property['type'] = 'array';
$property['items'] = $this->serializer
->normalize($list_data_definition
->getItemDefinition(), $format, $context);
if ($this
->requiredProperty($list_data_definition)) {
$property['minItems'] = 1;
}
if ($context['cardinality'] == 1) {
$single_property = $property['items'];
unset($property['items']);
unset($property['type']);
unset($property['minItems']);
$single_property = array_merge($single_property, $property);
$property = $single_property;
}
$normalized = [
'description' => t('Entity attributes'),
'type' => 'object',
'properties' => [],
];
$public_name = $context['name'];
$normalized['properties'][$public_name] = $property;
if ($this
->requiredProperty($list_data_definition)) {
$normalized['required'][] = $public_name;
}
return [
'type' => 'object',
'properties' => [
'attributes' => $normalized,
],
];
}
protected function isReferenceField(ListDataDefinitionInterface $entity) {
$item = $entity
->getItemDefinition();
if ($item instanceof ComplexDataDefinitionInterface) {
$main = $item
->getPropertyDefinition($item
->getMainPropertyName());
return $main instanceof DataReferenceTargetDefinition;
}
return FALSE;
}
}