SchemaFieldDefinitionNormalizer.php in JSON:API Extras 8.3
File
src/Normalizer/SchemaFieldDefinitionNormalizer.php
View source
<?php
namespace Drupal\jsonapi_extras\Normalizer;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\jsonapi_extras\ResourceType\ConfigurableResourceType;
use Drupal\schemata_json_schema\Normalizer\jsonapi\FieldDefinitionNormalizer as SchemataJsonSchemaFieldDefinitionNormalizer;
use Drupal\jsonapi\ResourceType\ResourceTypeRepository;
class SchemaFieldDefinitionNormalizer extends SchemataJsonSchemaFieldDefinitionNormalizer {
protected $resourceTypeRepository;
public function __construct(ResourceTypeRepository $resource_type_repository) {
$this->resourceTypeRepository = $resource_type_repository;
}
public function normalize($field_definition, $format = NULL, array $context = []) {
assert($field_definition instanceof FieldDefinitionInterface);
$normalized = parent::normalize($field_definition, $format, $context);
$bundle = empty($context['bundleId']) ? $context['entityTypeId'] : $context['bundleId'];
$resource_type = $this->resourceTypeRepository
->get($context['entityTypeId'], $bundle);
if (!$resource_type || !$resource_type instanceof ConfigurableResourceType) {
return $normalized;
}
$field_name = $context['name'];
$enhancer = $resource_type
->getFieldEnhancer($field_definition
->getName());
if (!$enhancer) {
return $normalized;
}
$parents = [
'properties',
'attributes',
'properties',
$field_name,
];
$original_field_schema = NestedArray::getValue($normalized, $parents);
$to_copy = [
'title',
'description',
];
$field_schema = array_merge($enhancer
->getOutputJsonSchema(), array_intersect_key($original_field_schema, array_flip($to_copy)));
NestedArray::setValue($normalized, $parents, $field_schema);
return $normalized;
}
}