clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,25 @@
<?php
namespace Drupal\jsonapi_schema\Annotation;
use Drupal\Component\Annotation\Plugin;
/**
* Defines a JSON Schema Type Mapper annotation object.
*
* Plugin Namespace: Plugin\jsonapi_schema\type_mapper.
*
* @ingroup third_party
*
* @Annotation
*/
class TypeMapper extends Plugin {
/**
* The TypeMapper plugin ID.
*
* @var string
*/
public $id;
}
@@ -0,0 +1,333 @@
<?php
namespace Drupal\jsonapi_schema\Controller;
use Drupal\Component\Utility\NestedArray;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi\ResourceType\ResourceTypeAttribute;
use Drupal\jsonapi\ResourceType\ResourceTypeField;
use Drupal\jsonapi\ResourceType\ResourceTypeRelationship;
use Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface;
use Drupal\jsonapi_schema\Routing\Routes;
use Drupal\jsonapi_schema\StaticDataDefinitionExtractor;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class JsonApiSchemaController extends ControllerBase {
const JSON_SCHEMA_DRAFT = 'https://json-schema.org/draft/2019-09/hyper-schema';
const JSONAPI_BASE_SCHEMA_URI = 'https://jsonapi.org/schema';
/**
* The JSON:API resource type repository.
*
* @var \Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface
*/
protected $resourceTypeRepository;
/**
* The serialization service.
*
* @var \Symfony\Component\Serializer\Normalizer\NormalizerInterface
*/
protected $normalizer;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The static data definition extractor.
*
* @var \Drupal\jsonapi_schema\StaticDataDefinitionExtractor
*/
protected $staticDataDefinitionExtractor;
/**
* JsonApiSchemaController constructor.
*
* @param \Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface $resource_type_repository
* The JSON:API resource type repository.
* @param \Symfony\Component\Serializer\Normalizer\NormalizerInterface $normalizer
* The serializer.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(ResourceTypeRepositoryInterface $resource_type_repository, NormalizerInterface $normalizer, EntityTypeManagerInterface $entity_type_manager, StaticDataDefinitionExtractor $static_data_definition_extractor) {
$this->resourceTypeRepository = $resource_type_repository;
$this->normalizer = $normalizer;
$this->entityTypeManager = $entity_type_manager;
$this->staticDataDefinitionExtractor = $static_data_definition_extractor;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('jsonapi.resource_type.repository'),
$container->get('serializer'),
$container->get('entity_type.manager'),
$container->get('jsonapi_schema.static_data_definition_extractor')
);
}
public function getEntrypointSchema(Request $request) {
$cacheability = new CacheableMetadata();
$cacheability->addCacheTags(['jsonapi_resource_types']);
$collection_links = array_values(array_map(function (ResourceType $resource_type) use ($cacheability) {
$schema_url = Url::fromRoute("jsonapi_schema.{$resource_type->getTypeName()}.collection")->setAbsolute()->toString(TRUE);
$cacheability->addCacheableDependency($schema_url);
return [
'href' => '{instanceHref}',
'rel' => 'related',
'title' => $this->getSchemaTitle($resource_type, 'collection'),
'targetMediaType' => 'application/vnd.api+json',
'targetSchema' => ['$ref' => $schema_url->getGeneratedUrl()],
'templatePointers' => [
'instanceHref' => "/links/{$resource_type->getTypeName()}/href",
],
'templateRequired' => ['instanceHref'],
];
}, array_filter($this->resourceTypeRepository->all(), function (ResourceType $resource_type) {
return !$resource_type->isInternal() && $resource_type->isLocatable();
})));
$schema = [
'$schema' => static::JSON_SCHEMA_DRAFT,
'$id' => $request->getUri(),
'allOf' => [
[
'$ref' => static::JSONAPI_BASE_SCHEMA_URI . '#/definitions/success',
],
[
'type' => 'object',
'links' => $collection_links,
],
],
];
$response = new CacheableJsonResponse($schema);
$response->addCacheableDependency($cacheability);
return $response;
}
public function getDocumentSchema(Request $request, $resource_type, $route_type) {
if (is_array($resource_type)) {
$titles = array_map(function ($type) use ($route_type) {
return $this->getSchemaTitle($this->resourceTypeRepository->getByTypeName($type), $route_type);
}, $resource_type);
$title = count($titles) === 2
? implode(' and ', $titles)
: implode(', ', array_slice($titles, 0, -1)) . ', and ' . end($titles);
}
else {
$title = $this->getSchemaTitle($this->resourceTypeRepository->getByTypeName($resource_type), $route_type);
}
$schema = [
'$schema' => static::JSON_SCHEMA_DRAFT,
'$id' => $request->getUri(),
'title' => $title,
'allOf' => [
[
'$ref' => static::JSONAPI_BASE_SCHEMA_URI,
],
[
'if' => [
'$ref' => static::JSONAPI_BASE_SCHEMA_URI . '#/definitions/success',
],
'then' => [
'type' => 'object',
'properties' => [
'data' => [
'$ref' => '#/definitions/data',
],
],
'required' => ['data'],
],
],
],
];
$cacheability = new CacheableMetadata();
$get_schema_ref = function ($resource_type) use ($cacheability) {
$schema_url = Url::fromRoute("jsonapi_schema.$resource_type.type")->setAbsolute()->toString(TRUE);
$cacheability->addCacheableDependency($schema_url);
return ['$ref' => $schema_url->getGeneratedUrl()];
};
$type_schema = is_array($resource_type)
? ['anyOf' => array_map($get_schema_ref, $resource_type)]
: $get_schema_ref($resource_type);
switch ($route_type) {
case 'item':
$schema['definitions']['data'] = $type_schema;
break;
case 'collection':
$schema['definitions']['data'] = [
'type' => 'array',
'items' => $type_schema,
];
break;
case 'relationship':
assert('not implemented');
break;
}
$response = new CacheableJsonResponse($schema);
$response->addCacheableDependency($cacheability);
return $response;
}
public function getResourceObjectSchema(Request $request, $resource_type) {
$resource_type = $this->resourceTypeRepository->getByTypeName($resource_type);
$schema = [
'$schema' => static::JSON_SCHEMA_DRAFT,
'$id' => $request->getUri(),
'title' => $this->getSchemaTitle($resource_type, 'item'),
'allOf' => [
[
'type' => 'object',
'properties' => [
'type' => ['$ref' => '#/definitions/type'],
],
],
[
'$ref' => static::JSONAPI_BASE_SCHEMA_URI . '#/definitions/resource',
]
],
'definitions' => [
'type' => ['const' => $resource_type->getTypeName()],
],
];
$cacheability = new CacheableMetadata();
$schema = $this->addFieldsSchema($schema, $resource_type);
$schema = $this->addRelationshipsSchemaLinks($schema, $resource_type, $cacheability);
$response = new CacheableJsonResponse($schema);
$response->addCacheableDependency($cacheability);
return $response;
}
protected function addFieldsSchema(array $schema, ResourceType $resource_type) {
// Filter out disabled fields.
$resource_fields = array_filter($resource_type->getFields(), function (ResourceTypeField $field) {
return $field->isFieldEnabled();
});
if (empty($resource_fields)) {
return $schema;
}
$schema['allOf'][0]['properties']['attributes'] = [
'$ref' => '#/definitions/attributes',
];
$normalizer = $this->normalizer;
$entity_type = $this->entityTypeManager->getDefinition($resource_type->getEntityTypeId());
$bundle = $resource_type->getBundle();
$fields = array_reduce($resource_fields, function ($carry, ResourceTypeField $field) use ($normalizer, $resource_type, $entity_type, $bundle) {
$field_schema = $normalizer->normalize(
$this->staticDataDefinitionExtractor->extractField($entity_type, $bundle, $field->getInternalName()),
'schema_json',
[
'name' => $field->getPublicName(),
'resource_type' => $resource_type,
]
);
$fields_member = $field instanceof ResourceTypeAttribute ? 'attributes' : 'relationships';
return NestedArray::mergeDeep($carry, [
'type' => 'object',
'properties' => [
$fields_member => $field_schema,
],
]);
}, []);
$field_definitions = NestedArray::getValue($fields, ['properties']) ?: [];
if (!empty($field_definitions['attributes'])) {
$field_definitions['attributes']['additionalProperties'] = FALSE;
}
if (!empty($field_definitions['relationships'])) {
$field_definitions['relationships']['additionalProperties'] = FALSE;
}
$schema['definitions'] = NestedArray::mergeDeep($schema['definitions'], $field_definitions);
return $schema;
}
protected static function addRelationshipsSchemaLinks(array $schema, ResourceType $resource_type, CacheableMetadata $cacheability) {
$resource_relationships = array_filter($resource_type->getFields(), function (ResourceTypeField $field) {
return $field->isFieldEnabled() && $field instanceof ResourceTypeRelationship;
});
if (empty($resource_relationships)) {
return $schema;
}
$schema['allOf'][0]['properties']['relationships'] = [
'$ref' => '#/definitions/relationships',
];
$relationships = array_reduce($resource_relationships, function ($relationships, ResourceTypeRelationship $relationship) use ($resource_type, $cacheability) {
if ($resource_type->isInternal() || !Routes::hasNonInternalTargetResourceTypes($relationship->getRelatableResourceTypes())) {
return $relationships;
}
$field_name = $relationship->getPublicName();
$resource_type_name = $resource_type->getTypeName();
$related_route_name = "jsonapi_schema.{$resource_type_name}.$field_name.related";
$related_schema_uri = Url::fromRoute($related_route_name)->setAbsolute()->toString(TRUE);
$cacheability->addCacheableDependency($related_schema_uri);
return NestedArray::mergeDeep($relationships, [
$field_name => [
'links' => [
[
'href' => '{instanceHref}',
'rel' => 'related',
'targetMediaType' => 'application/vnd.api+json',
'targetSchema' => ['$ref' => $related_schema_uri->getGeneratedUrl()],
'templatePointers' => [
'instanceHref' => '/links/related/href',
],
'templateRequired' => ['instanceHref'],
],
],
],
]);
}, []);
$schema['definitions']['relationships'] = NestedArray::mergeDeep(
empty($schema['definitions']['relationships']) ? [] : $schema['definitions']['relationships'],
['properties' => $relationships]
);
return $schema;
}
/**
* Gets a schema title.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type
* A JSON:API resource type for which to generate a title.
* @param $schema_type
* The type of schema. Either 'collection' or 'item'.
*
* @return \Drupal\Core\StringTranslation\TranslatableMarkup
* The schema title.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
protected function getSchemaTitle(ResourceType $resource_type, $schema_type) {
$entity_type = $this->entityTypeManager->getDefinition($resource_type->getEntityTypeId());
$entity_type_label = $schema_type === 'collection' ? $entity_type->getPluralLabel() : $entity_type->getSingularLabel();
if ($bundle_type = $entity_type->getBundleEntityType()) {
$bundle = $this->entityTypeManager->getStorage($bundle_type)->load($resource_type->getBundle());
return $this->t(rtrim('@bundle_label @entity_type_label'), [
'@bundle_label' => Unicode::ucfirst($bundle->label()),
'@entity_type_label' => $entity_type_label,
]);
}
else {
return $this->t(rtrim('@entity_type_label'), [
'@entity_type_label' => Unicode::ucfirst($entity_type_label),
]);
}
}
}
@@ -0,0 +1,71 @@
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Core\TypedData\ComplexDataDefinitionInterface;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\DataReferenceTargetDefinition;
use Drupal\Component\Utility\NestedArray;
/**
* Normalizer for ComplexDataDefinitionInterface.
*
* ComplexDataDefinitions represent objects - compound values whose objects
* have string keys. Almost all fields are complex in this way, with their key
* data stored in an object property of "value". In turn, these objects are
* wrapped in an array which is normalized by ListDataDefinitionNormalizer.
*/
class ComplexDataDefinitionNormalizer extends DataDefinitionNormalizer {
/**
* The interface or class that this Normalizer supports.
*
* @var string
*/
protected $supportedInterfaceOrClass = ComplexDataDefinitionInterface::class;
/**
* {@inheritdoc}
*/
public function normalize($entity, $format = NULL, array $context = []) {
assert($entity instanceof ComplexDataDefinitionInterface);
$context['parent'] = $entity;
$normalized = $this->extractPropertyData($entity);
$normalized['type'] = 'object';
// Retrieve 'properties' and possibly 'required' nested arrays.
$property_definitions = array_filter($entity->getPropertyDefinitions(), function (DataDefinitionInterface $item) {
return !$item->isInternal();
});
$properties = $this->normalizeProperties(
$property_definitions,
$format,
$context
);
$normalized = NestedArray::mergeDeep($normalized, $properties);
if (count($property_definitions) == 1) {
// If there is only one property, JSON API does not use the complex data.
return $normalized['properties'][key($property_definitions)];
}
return $normalized;
}
/**
* Determine if the current field is a reference field.
*
* @param \Drupal\Core\TypedData\ComplexDataDefinitionInterface $entity
* The complex data definition to be checked.
* @param array $context
* The current serializer context.
*
* @return bool
* TRUE if it is a reference, FALSE otherwise.
*/
protected function isReferenceField(ComplexDataDefinitionInterface $entity, array $context = NULL) {
$main = $entity->getPropertyDefinition($entity->getMainPropertyName());
// @todo use an interface or API call instead of an object check.
return ($main instanceof DataReferenceTargetDefinition);
}
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Core\TypedData\DataDefinitionInterface;
/**
* Data definition normalizer.
*/
class DataDefinitionDatetimeNormalizer extends DataDefinitionNormalizer {
/**
* {@inheritdoc}
*/
protected $supportedDataTypes = ['datetime_iso8601'];
/**
* {@inheritdoc}
*/
protected function extractPropertyData(DataDefinitionInterface $property, array $context = []) {
$value = parent::extractPropertyData($property);
$value['type'] = 'string';
$value['format'] = 'date';
return $value;
}
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Core\TypedData\DataDefinitionInterface;
/**
* Data definition normalizer.
*/
class DataDefinitionEmailNormalizer extends DataDefinitionNormalizer {
/**
* {@inheritdoc}
*/
protected $supportedDataTypes = ['email'];
/**
* {@inheritdoc}
*/
protected function extractPropertyData(DataDefinitionInterface $property, array $context = []) {
$value = parent::extractPropertyData($property);
$value['type'] = 'string';
$value['format'] = 'email';
return $value;
}
}
@@ -0,0 +1,26 @@
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Core\TypedData\DataDefinitionInterface;
/**
* Data definition normalizer.
*/
class DataDefinitionEntityReferenceNormalizer extends DataDefinitionNormalizer {
/**
* {@inheritdoc}
*/
protected $supportedDataTypes = ['entity_reference'];
/**
* {@inheritdoc}
*/
protected function extractPropertyData(DataDefinitionInterface $property, array $context = []) {
$value = parent::extractPropertyData($property);
$value['type'] = 'object';
return $value;
}
}
@@ -0,0 +1,227 @@
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\BooleanItem;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\ListDataDefinitionInterface;
use Drupal\Core\TypedData\OptionsProviderInterface;
use Drupal\serialization\Normalizer\NormalizerBase;
/**
* Normalizer for DataDefinitionInterface instances.
*
* DataDefinitionInterface is the ultimate parent to all data definitions. This
* service must always be low priority for data definitions, otherwise the
* simpler normalization process it supports will take precedence over all the
* complexities most entity properties contain before reaching this level.
*
* DataDefinitionNormalizer produces scalar value definitions.
*
* All the TypedData normalizers extend from this class.
*/
class DataDefinitionNormalizer extends NormalizerBase {
const JSON_TYPES = ['null', 'boolean', 'string', 'number', 'integer', 'array', 'object'];
/**
* The formats that the Normalizer can handle.
*
* @var array
*/
protected $format = 'schema_json';
/**
* The interface or class that this Normalizer supports.
*
* @var string
*/
protected $supportedInterfaceOrClass = DataDefinitionInterface::class;
/**
* The supported data type.
*
* @var string[]
*/
protected $supportedDataTypes = [];
/**
* {@inheritdoc}
*/
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') {
/** @var \Drupal\Core\Field\TypedData\FieldItemDataDefinitionInterface $parent */
$parent = $context['parent'];
if ($maxLength = $parent->getSetting('max_length')) {
$property['maxLength'] = $maxLength;
}
// Get possible options for anyOf/oneOf.
if (!empty($context['resource_type'])) {
/** @var \Drupal\jsonapi\ResourceType\ResourceType $resource_type */
$resource_type = $context['resource_type'];
$field_definition = $context['parent']->getFieldDefinition();
$field_storage_definition = $field_definition->getFieldStorageDefinition();
if (is_subclass_of($field_storage_definition, ListDataDefinitionInterface::class)) {
$class = $field_storage_definition->getItemDefinition()->getClass();
if (is_subclass_of($class, OptionsProviderInterface::class) && $class != BooleanItem::class) {
$entity_type = $resource_type->getEntityTypeId();
$bundle = $resource_type->getBundle();
/** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
$entity_type_manager = \Drupal::entityTypeManager();
$entity_type_definition = $entity_type_manager->getDefinition($entity_type);
$bundle_key = $entity_type_definition->getKey('bundle');
/** @var \Drupal\Core\Entity\FieldableEntityInterface $mock_entity */
$mock_entity = $entity_type_manager->getStorage($entity_type)->create([$bundle_key => $bundle]);
$allowed_values = $field_storage_definition->getOptionsProvider($field_definition->getName(), $mock_entity)->getPossibleOptions();
// Include titles for UI integration.
// @see https://json-schema.org/understanding-json-schema/reference/generic.html?highlight=enum#annotations
$composition = $context['cardinality'] === FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED ? 'anyOf' : 'oneOf';
array_walk($allowed_values, function (&$v, $k) { $v = ['const' => $k, 'title' => $v]; });
$property[$composition] = array_values($allowed_values);
}
}
}
}
if (!is_object($property) && !isset($property['title']) && isset($context['name'])) {
$property['title'] = $context['name'];
}
// If the property type is "float", change it to "number".
if (!is_object($property) && $property['type'] == 'float') {
$property['type'] = 'number';
}
$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;
}
/**
* Extracts property details from a data definition.
*
* This method includes mapping primitive types in Drupal to JSON Schema
* type and format descriptions. This method is invoked by several of the
* normalizers.
*
* @param \Drupal\Core\TypedData\DataDefinitionInterface $property
* The data definition from which to extract values.
* @param array $context
* Serializer context.
*
* @return array
* Discrete values of the property definition
*/
protected function extractPropertyData(DataDefinitionInterface $property, array $context = []) {
$value = ['type' => $property->getDataType()];
if ($item = $property->getLabel()) {
$value['title'] = $item;
}
if ($item = $property->getDescription()) {
$value['description'] = addslashes(strip_tags($item));
}
return $value;
}
/**
* Normalize an array of data definitions.
*
* This normalization process gets an array of properties and an array of
* properties that are required by name. This is needed by the
* SchemataSchemaNormalizer, otherwise it would have been placed in
* DataDefinitionNormalizer.
*
* @param \Drupal\Core\TypedData\DataDefinitionInterface[] $items
* An array of data definition properties to be normalized.
* @param string $format
* Format identifier of the current serialization process.
* @param array $context
* Operating context of the serializer.
*
* @return array
* Array containing one or two nested arrays.
* - properties: The array of all normalized properties.
* - required: The array of required properties by name.
*/
protected function normalizeProperties(array $items, $format, array $context = []) {
$normalized = [];
foreach ($items as $name => $property) {
$context['name'] = $name;
$item = $this->serializer->normalize($property, $format, $context);
if (!empty($item)) {
$normalized = NestedArray::mergeDeep($normalized, $item);
}
}
return $normalized;
}
/**
* Determine if the given property is a required element of the schema.
*
* @param \Drupal\Core\TypedData\DataDefinitionInterface $property
* The data property to be evaluated.
*
* @return bool
* Whether the property should be treated as required for schema
* purposes.
*/
protected function requiredProperty(DataDefinitionInterface $property) {
// We must test all three values, because it may be possible a computed
// field has its read-only value explicitly set to a contradictory value, in
// which case the computed state is not taken into consideration. This is
// thus the safest test.
return $property->isRequired()
&& (!$property->isReadOnly() && !$property->isComputed());
}
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = NULL, array $context = []): bool {
return parent::supportsNormalization($data, $format)
&& $data instanceof DataDefinitionInterface
&& (empty($this->supportedDataTypes) || in_array($data->getDataType(), $this->supportedDataTypes));
}
/**
* {@inheritdoc}
*/
public function supportsDenormalization($data, $type, $format = NULL, array $context = []): bool {
return FALSE;
}
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = NULL, array $context = []) {
throw new \RuntimeException('Denormalization is not supported.');
}
}
@@ -0,0 +1,26 @@
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Core\TypedData\DataDefinitionInterface;
/**
* Data definition normalizer.
*/
class DataDefinitionStringNormalizer extends DataDefinitionNormalizer {
/**
* {@inheritdoc}
*/
protected $supportedDataTypes = ['filter_format', 'language_reference'];
/**
* {@inheritdoc}
*/
protected function extractPropertyData(DataDefinitionInterface $property, array $context = []) {
$value = parent::extractPropertyData($property);
$value['type'] = 'string';
return $value;
}
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Core\TypedData\DataDefinitionInterface;
/**
* Data definition normalizer.
*/
class DataDefinitionTimestampNormalizer extends DataDefinitionNormalizer {
/**
* {@inheritdoc}
*/
protected $supportedDataTypes = ['timestamp'];
/**
* {@inheritdoc}
*/
protected function extractPropertyData(DataDefinitionInterface $property, array $context = []) {
$value = parent::extractPropertyData($property);
$value['type'] = 'string';
$value['format'] = 'date-time';
return $value;
}
}
@@ -0,0 +1,26 @@
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Core\TypedData\DataDefinitionInterface;
/**
* Data definition normalizer.
*/
class DataDefinitionUndefinedNormalizer extends DataDefinitionNormalizer {
/**
* {@inheritdoc}
*/
protected $supportedDataTypes = ['undefined'];
/**
* {@inheritdoc}
*/
protected function extractPropertyData(DataDefinitionInterface $property, array $context = []) {
return isset($context['name'])
? (object) ['title' => $context['name']]
: (object) [];
}
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Core\TypedData\DataDefinitionInterface;
/**
* Data definition normalizer.
*/
class DataDefinitionUriNormalizer extends DataDefinitionNormalizer {
/**
* {@inheritdoc}
*/
protected $supportedDataTypes = ['uri'];
/**
* {@inheritdoc}
*/
protected function extractPropertyData(DataDefinitionInterface $property, array $context = []) {
$value = parent::extractPropertyData($property);
$value['type'] = 'string';
$value['format'] = 'uri';
return $value;
}
}
@@ -0,0 +1,62 @@
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
/**
* Normalizer for FieldDefinitionInterface objects.
*
* This normalizes the variant of data fields particular to the Field system.
* By accessing this via the FieldDefinitionInterface, there is greater access
* to some of the methods providing deeper schema properties.
*/
class FieldDefinitionNormalizer extends ListDataDefinitionNormalizer {
/**
* The interface or class that this Normalizer supports.
*
* @var string
*/
protected $supportedInterfaceOrClass = FieldDefinitionInterface::class;
/**
* {@inheritdoc}
*/
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', $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', $field_name, 'maxItems'],
$cardinality
);
}
return $normalized;
}
}
@@ -0,0 +1,93 @@
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Core\TypedData\ComplexDataDefinitionInterface;
use Drupal\Core\TypedData\DataReferenceTargetDefinition;
use Drupal\Core\TypedData\ListDataDefinitionInterface;
/**
* Normalizer for ListDataDefinitionInterface objects.
*
* Almost all entity properties in the system are a list of values, each value
* in the "List" might be a ComplexDataDefinitionInterface (an object) or it
* might be more of a scalar.
*/
class ListDataDefinitionNormalizer extends DataDefinitionNormalizer {
/**
* The interface or class that this Normalizer supports.
*
* @var string
*/
protected $supportedInterfaceOrClass = ListDataDefinitionInterface::class;
/**
* {@inheritdoc}
*/
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';
// This retrieves the definition common to ever item in the list, and
// serializes it so we can define how members of the array should look.
// There are no lists that might contain items of different types.
$property['items'] = $this->serializer->normalize(
$list_data_definition->getItemDefinition(),
$format,
$context
);
// FieldDefinitionInterface::isRequired() explicitly indicates there must be
// at least one item in the list. Extending this reasoning, the same must be
// true of all ListDataDefinitions.
if ($this->requiredProperty($list_data_definition)) {
$property['minItems'] = 1;
}
if (!empty($context['cardinality']) && $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 $normalized;
}
/**
* Determine if the current field is a reference field.
*
* @param \Drupal\Core\TypedData\ListDataDefinitionInterface $entity
* The list definition to be checked.
*
* @return bool
* TRUE if it is a reference, FALSE otherwise.
*/
protected function isReferenceField(ListDataDefinitionInterface $entity) {
$item = $entity->getItemDefinition();
if ($item instanceof ComplexDataDefinitionInterface) {
$main = $item->getPropertyDefinition($item->getMainPropertyName());
// @todo use an interface or API call instead of an object check.
return ($main instanceof DataReferenceTargetDefinition);
}
return FALSE;
}
}
@@ -0,0 +1,166 @@
<?php
namespace Drupal\jsonapi_schema\Normalizer;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\FieldTypePluginManagerInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface;
/**
* Normalizer for RelationshipFieldDefinitionNormalizer objects.
*
* This normalizes the JSON API relationships. This normalizer shortcuts the
* recursion for the entity reference field. A JSON API relationship is what it
* is, regardless of how Drupal stores the relationship.
*/
class RelationshipFieldDefinitionNormalizer extends ListDataDefinitionNormalizer {
/**
* The interface or class that this Normalizer supports.
*
* @var string
*/
protected $supportedInterfaceOrClass = FieldDefinitionInterface::class;
/**
* The field type plugin manager.
*
* @var \Drupal\Core\Field\FieldTypePluginManagerInterface
*/
protected $fieldTypeManager;
/**
* RelationshipFieldDefinitionNormalizer constructor.
*
* @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_manager
* The field type plugin manager.
*/
public function __construct(FieldTypePluginManagerInterface $field_type_manager) {
$this->fieldTypeManager = $field_type_manager;
}
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = NULL, array $context = []): bool {
if (!parent::supportsNormalization($data, $format)) {
return FALSE;
}
$type = $data->getItemDefinition()->getFieldDefinition()->getType();
$class = $this->fieldTypeManager->getPluginClass($type);
// Deal only with entity reference fields and descendants.
return $class == EntityReferenceItem::class || is_subclass_of($class, EntityReferenceItem::class);
}
/**
* {@inheritdoc}
*/
public function normalize($entity, $format = NULL, array $context = []) {
$cardinality = $entity->getFieldStorageDefinition()->getCardinality();
$context['cardinality'] = $cardinality;
assert($entity instanceof FieldDefinitionInterface);
$normalized = [
'description' => t('Entity relationships'),
'properties' => [$context['name'] => $this->normalizeRelationship($entity, $format, $context)],
'type' => 'object',
];
// Specify non-contextual default value as an example.
$default_value = $entity->getDefaultValueLiteral();
if (!empty($default_value)) {
$normalized['properties'][$context['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) {
$normalized['properties'][$context['name']]['maxItems'] = $cardinality;
}
if ($this->requiredProperty($entity)) {
$normalized['required'][] = $context['name'];
}
return $normalized;
}
/**
* Normalizes the relationship.
*
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The field definition.
*
* @return array
* The normalized relationship.
*/
protected function normalizeRelationship(FieldDefinitionInterface $field_definition, $format = NULL, $context = []) {
$resource_type_repository = \Drupal::service('jsonapi.resource_type.repository');
assert($resource_type_repository instanceof ResourceTypeRepositoryInterface);
// A relationship has very similar schema every time.
$resource_identifier_object = [
'type' => 'object',
'required' => ['type', 'id'],
'properties' => [
'type' => ['type' => 'string', 'title' => t('Referenced resource')],
'id' => [
'type' => 'string',
'title' => t('Resource ID'),
'format' => 'uuid',
'maxLength' => 128,
],
],
];
// Handle the multivalue variant.
$cardinality = $field_definition
->getFieldStorageDefinition()
->getCardinality();
if ($target_entity_type = $field_definition->getSetting('target_type')) {
$handler_settings = $field_definition->getSetting('handler_settings');
$target_bundles = empty($handler_settings['target_bundles']) ?
[$target_entity_type] :
array_values($handler_settings['target_bundles']);
$target_resource_types = array_map(
function ($bundle) use ($target_entity_type, $resource_type_repository) {
return $resource_type_repository->get(
$target_entity_type,
$bundle ?: $target_entity_type
);
return $resource_type->getTypeName();
},
$target_bundles
);
$enum = array_map(function (ResourceType $resource_type) {
return $resource_type->getTypeName();
}, array_filter($target_resource_types));
}
$meta = $this->serializer->normalize($field_definition->getItemDefinition(), $format, $context);
if ($cardinality == 1) {
$data = $resource_identifier_object;
if (!empty($enum)) {
$data['properties']['type']['enum'] = $enum;
$data['properties']['meta'] = $meta;
}
}
else {
$data = [
'type' => 'array',
'items' => $resource_identifier_object,
];
if (!empty($enum)) {
$data['items']['properties']['type']['enum'] = $enum;
$data['items']['properties']['meta'] = $meta;
}
}
$normalized = [
'type' => 'object',
'properties' => [
'data' => $data,
],
'title' => $field_definition->getLabel(),
];
return $normalized;
}
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\jsonapi_schema\Plugin\jsonapi_hypermedia\LinkProvider;
use Drupal\jsonapi_hypermedia\Annotation\JsonapiHypermediaLinkProvider;
/**
* Class CollectionTopLevelSchemaLinkProvider.
*
* @JsonapiHypermediaLinkProvider(
* id = "jsonapi_shema.top_level.collection",
* link_relation_type = "describedby",
* link_context = {
* "top_level_object" = "collection",
* },
* )
*
* @internal
*/
final class CollectionTopLevelSchemaLinkProvider extends TopLevelSchemaLinkProviderBase {
/**
* {@inheritdoc}
*/
protected static $schemaRouteType = 'collection';
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\jsonapi_schema\Plugin\jsonapi_hypermedia\LinkProvider;
use Drupal\jsonapi_hypermedia\Annotation\JsonapiHypermediaLinkProvider;
/**
* Class CollectionTopLevelSchemaLinkProvider.
*
* @JsonapiHypermediaLinkProvider(
* id = "jsonapi_shema.top_level.entrypoint",
* link_relation_type = "describedby",
* link_context = {
* "top_level_object" = "entrypoint",
* },
* )
*
* @internal
*/
final class EntrypointSchemaLinkProvider extends TopLevelSchemaLinkProviderBase {
/**
* {@inheritdoc}
*/
protected static $schemaRouteType = 'entrypoint';
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\jsonapi_schema\Plugin\jsonapi_hypermedia\LinkProvider;
use Drupal\jsonapi_hypermedia\Annotation\JsonapiHypermediaLinkProvider;
/**
* Class IndividualTopLevelSchemaLinkProvider.
*
* @JsonapiHypermediaLinkProvider(
* id = "jsonapi_shema.top_level.individual",
* link_relation_type = "describedby",
* link_context = {
* "top_level_object" = "individual",
* },
* )
*
* @internal
*/
final class IndividualTopLevelSchemaLinkProvider extends TopLevelSchemaLinkProviderBase {
/**
* {@inheritdoc}
*/
protected static $schemaRouteType = 'item';
}
@@ -0,0 +1,38 @@
<?php
namespace Drupal\jsonapi_schema\Plugin\jsonapi_hypermedia\LinkProvider;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Url;
use Drupal\jsonapi\JsonApiResource\ResourceObject;
use Drupal\jsonapi_hypermedia\AccessRestrictedLink;
use Drupal\jsonapi_hypermedia\Annotation\JsonapiHypermediaLinkProvider;
use Drupal\jsonapi_hypermedia\Plugin\LinkProviderBase;
/**
* Class ResourceObjectSchemaLinkProvider.
*
* @JsonapiHypermediaLinkProvider(
* id = "jsonapi_shema.resource_object",
* link_relation_type = "describedby",
* link_context = {
* "resource_object" = true,
* },
* )
*
* @internal
*/
final class ResourceObjectSchemaLinkProvider extends LinkProviderBase {
/**
* {@inheritdoc}
*/
public function getLink($context) {
assert($context instanceof ResourceObject);
$resource_type_name = $context->getResourceType()->getTypeName();
$resource_schema_uri = Url::fromRoute("jsonapi_schema.$resource_type_name.type");
return AccessRestrictedLink::createLink(AccessResult::allowed(), new CacheableMetadata(), $resource_schema_uri, $this->getLinkRelationType());
}
}
@@ -0,0 +1,73 @@
<?php
namespace Drupal\jsonapi_schema\Plugin\jsonapi_hypermedia\LinkProvider;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi\Routing\Routes;
use Drupal\jsonapi_hypermedia\AccessRestrictedLink;
use Drupal\jsonapi_hypermedia\Plugin\LinkProviderBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;
/**
* Class TopLevelSchemaLinkProviderBase.
*
* @internal
*/
abstract class TopLevelSchemaLinkProviderBase extends LinkProviderBase implements ContainerFactoryPluginInterface {
protected static $schemaRouteType = NULL;
/**
* The current route match.
*
* @var \Drupal\Core\Routing\RouteMatchInterface
*/
protected $currentRouteMatch;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
assert(in_array(static::$schemaRouteType, ['item', 'collection', 'entrypoint'], TRUE));
$provider = new static($configuration, $plugin_id, $plugin_definition);
$provider->setCurrentRouteMatch($container->get('current_route_match'));
return $provider;
}
/**
* Sets the current route match.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
*/
public function setCurrentRouteMatch(RouteMatchInterface $route_match) {
$this->currentRouteMatch = $route_match;
}
/**
* {@inheritdoc}
*/
public function getLink($context) {
assert($context instanceof JsonApiDocumentTopLevel);
if (static::$schemaRouteType === 'entrypoint') {
$schema_route_name = "jsonapi_schema." . static::$schemaRouteType;
}
else {
$route = $this->currentRouteMatch->getRouteObject();
assert($route instanceof Route);
if ($resource_type = $route->getDefault(Routes::RESOURCE_TYPE_KEY)) {
$schema_route_name = "jsonapi_schema.{$resource_type}." . static::$schemaRouteType;
}
}
return !empty($schema_route_name)
? AccessRestrictedLink::createLink(AccessResult::allowed(), new CacheableMetadata(), new Url($schema_route_name), $this->getLinkRelationType())
: AccessRestrictedLink::createInaccessibleLink(AccessResult::allowed());
}
}
@@ -0,0 +1,130 @@
<?php
namespace Drupal\jsonapi_schema\Routing;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface;
use Drupal\jsonapi\Routing\Routes as JsonApiRoutes;
use Drupal\jsonapi_schema\Controller\JsonApiSchemaController;
use Drupal\Core\Routing\RouteObjectInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
class Routes implements ContainerInjectionInterface {
const CONTROLLER_NAME = JsonApiSchemaController::class;
const RESOURCE_TYPE_PARAMETER_KEY = 'resource_type';
const ROUTE_TYPE_PARAMETER_KEY = 'route_type';
/**
* @var \Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface
*/
protected $resourceTypeRepository;
protected $jsonApiRoutes;
protected $jsonApiBasePath;
protected $entityFieldManager;
public function __construct(ResourceTypeRepositoryInterface $resource_type_repository, EntityFieldManagerInterface $entity_field_manager, JsonApiRoutes $jsonapi_routes, $jsonapi_base_path) {
$this->resourceTypeRepository = $resource_type_repository;
$this->entityFieldManager = $entity_field_manager;
$this->jsonApiRoutes = $jsonapi_routes;
$this->jsonApiBasePath = $jsonapi_base_path;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('jsonapi.resource_type.repository'),
$container->get('entity_field.manager'),
JsonApiRoutes::create($container),
$container->getParameter('jsonapi.base_path')
);
}
public function routes() {
$jsonapi_schema_routes = new RouteCollection();
$entrypoint_schema_route = new Route($this->jsonApiBasePath . '/schema');
$entrypoint_schema_route->addDefaults([
RouteObjectInterface::CONTROLLER_NAME => static::CONTROLLER_NAME . '::getEntrypointSchema',
]);
$jsonapi_schema_routes->add("jsonapi_schema.entrypoint", $entrypoint_schema_route);
foreach ($this->resourceTypeRepository->all() as $resource_type) {
if ($resource_type->isInternal()) {
continue;
}
$resource_type_name = $resource_type->getTypeName();
$base_path = $this->jsonApiBasePath . $resource_type->getPath();
$individual_document_schema_route = new Route($base_path . '/schema');
$individual_document_schema_route->addDefaults([
RouteObjectInterface::CONTROLLER_NAME => static::CONTROLLER_NAME . '::getDocumentSchema',
static::ROUTE_TYPE_PARAMETER_KEY => 'item',
static::RESOURCE_TYPE_PARAMETER_KEY => $resource_type_name,
]);
$collection_document_schema_route = new Route($base_path . '/collection/schema');
$collection_document_schema_route->addDefaults([
RouteObjectInterface::CONTROLLER_NAME => static::CONTROLLER_NAME . '::getDocumentSchema',
static::ROUTE_TYPE_PARAMETER_KEY => 'collection',
static::RESOURCE_TYPE_PARAMETER_KEY => $resource_type_name,
]);
$resource_object_schema_route = new Route($base_path . '/resource/schema');
$resource_object_schema_route->addDefaults([
RouteObjectInterface::CONTROLLER_NAME => static::CONTROLLER_NAME . '::getResourceObjectSchema',
static::ROUTE_TYPE_PARAMETER_KEY => 'type',
static::RESOURCE_TYPE_PARAMETER_KEY => $resource_type_name,
]);
if ($resource_type->isLocatable()) {
$jsonapi_schema_routes->add("jsonapi_schema.$resource_type_name.collection", $collection_document_schema_route);
}
$jsonapi_schema_routes->add("jsonapi_schema.$resource_type_name.item", $individual_document_schema_route);
$jsonapi_schema_routes->add("jsonapi_schema.$resource_type_name.type", $resource_object_schema_route);
foreach ($resource_type->getRelatableResourceTypes() as $public_field_name => $target_resource_types) {
if ($resource_type->isInternal() || !Routes::hasNonInternalTargetResourceTypes($target_resource_types)) {
continue;
}
$is_to_one_relationship = $resource_type->getFieldByPublicName($public_field_name)->hasOne();
$public_target_resource_types = array_filter($target_resource_types, function (ResourceType $resource_type) {
return !$resource_type->isInternal();
});
$public_target_resource_type_names = array_map(function (ResourceType $resource_type) {
return $resource_type->getTypeName();
}, $public_target_resource_types);
$related_document_schema_route = new Route($base_path . "/resource/relationships/$public_field_name/related/schema");
$related_document_schema_route->addDefaults([
RouteObjectInterface::CONTROLLER_NAME => static::CONTROLLER_NAME . '::getDocumentSchema',
static::ROUTE_TYPE_PARAMETER_KEY => $is_to_one_relationship ? 'item' : 'collection',
static::RESOURCE_TYPE_PARAMETER_KEY => count($public_target_resource_type_names) > 1
? $public_target_resource_type_names
: reset($public_target_resource_type_names),
]);
$jsonapi_schema_routes->add("jsonapi_schema.$resource_type_name.$public_field_name.related", $related_document_schema_route);
//$relationship_document_schema_route = new Route($base_path . "/resource/relationships/$public_field_name/schema");
}
}
$jsonapi_schema_routes->addRequirements(['_access' => 'TRUE']);
return $jsonapi_schema_routes;
}
/**
* Determines if an array of resource types has any non-internal ones.
*
* @param \Drupal\jsonapi\ResourceType\ResourceType[] $resource_types
* The resource types to check.
*
* @return bool
* TRUE if there is at least one non-internal resource type in the given
* array; FALSE otherwise.
*/
public static function hasNonInternalTargetResourceTypes(array $resource_types) {
return array_reduce($resource_types, function ($carry, ResourceType $target) {
return $carry || !$target->isInternal();
}, FALSE);
}
}
@@ -0,0 +1,175 @@
<?php
namespace Drupal\jsonapi_schema;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Config\Entity\ConfigEntityTypeInterface;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\ListDataDefinition;
use Drupal\Core\TypedData\ListDataDefinitionInterface;
use Drupal\Core\TypedData\MapDataDefinition;
use Drupal\Core\TypedData\TypedDataManagerInterface;
/**
* Extracts the data definition for entities of an entity type.
*/
class StaticDataDefinitionExtractor {
/**
* A config entity ID used to determine schema of the config entity type.
*/
const BOGUS_CONFIG_ENTITY_ID = 'ID';
/**
* The typed data manager used for creating the data types.
*
* @var \Drupal\Core\TypedData\TypedDataManagerInterface
*/
private $typedDataManager;
/**
* The typed config manager.
*
* @var \Drupal\Core\Config\TypedConfigManagerInterface
*/
private $typedConfigManager;
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
private $entityFieldManager;
/**
* The cached definitions.
*
* @var \Drupal\Core\TypedData\MapDataDefinition[]
*/
private $definitions;
/**
* StaticDataDefinitionExtractor constructor.
*
* @param \Drupal\Core\TypedData\TypedDataManagerInterface
* The typed data manager used for creating the data types.
* @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config_manager
* The typed config manager.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
*/
public function __construct(TypedDataManagerInterface $typed_data_manager, TypedConfigManagerInterface $typed_config_manager, EntityFieldManagerInterface $entity_field_manager) {
$this->typedDataManager = $typed_data_manager;
$this->typedConfigManager = $typed_config_manager;
$this->entityFieldManager = $entity_field_manager;
}
/**
* Extracts the data definition information for an entity type and bundle.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type to extract the data definitions for.
* @param string $bundle
* The entity bundle.
*
* @return \Drupal\Core\TypedData\DataDefinition|\Drupal\Core\TypedData\MapDataDefinition
* The collection of data definitions, one for each field.
*
* @throws \LogicException
* If the entity type is neither configuration or content.
*/
public function extract(EntityTypeInterface $entity_type, $bundle) {
$data_type = sprintf('entity:%s:%s', $entity_type->id(), $bundle);
if (isset($this->definitions[$data_type])) {
return $this->definitions[$data_type];
}
if ($entity_type instanceof ContentEntityTypeInterface) {
$definition = $this->extractContentEntityType($entity_type, $bundle);
}
else if ($entity_type instanceof ConfigEntityTypeInterface) {
$definition = $this->extractConfigEntityType($entity_type, $bundle);
}
else {
throw new \LogicException('Only configuration and content entities are supported.');
}
$this->definitions[$data_type] = $definition;
return $definition;
}
public function extractField(EntityTypeInterface $entity_type, $bundle, $field_name) {
$definition = $this->extract($entity_type, $bundle);
return $definition->getPropertyDefinition($field_name)
?: DataDefinition::createFromDataType('undefined');
}
private function extractContentEntityType(ContentEntityTypeInterface $entity_type, $bundle) {
$data_type = sprintf('entity:%s', $entity_type->id());
if ($entity_type->getBundleEntityType()) {
$data_type .= ':' . $bundle;
}
return $this->typedDataManager->createDataDefinition($data_type);
}
private function extractConfigEntityType(ConfigEntityTypeInterface $entity_type, $bundle) {
$data_type = sprintf('entity:%s', $entity_type->id());
if ($entity_type->hasKey('bundle')) {
$data_type .= ':' . $bundle;
}
$config_definition = $this->typedConfigManager->getDefinition(
sprintf('%s.%s', $entity_type->getConfigPrefix(), static::BOGUS_CONFIG_ENTITY_ID),
FALSE
);
$definition = MapDataDefinition::createFromDataType($data_type);
foreach ($entity_type->getPropertiesToExport(static::BOGUS_CONFIG_ENTITY_ID) as $field_name) {
$field_schema = NestedArray::getValue($config_definition, ['mapping', $field_name]) ?: [];
$definition->setPropertyDefinition($field_name, $this->createDataDefinition($field_schema));
}
return $definition;
}
private function createDataDefinition($field_schema) {
if (!isset($field_schema['type'])) {
return DataDefinition::createFromDataType('undefined');
}
$data_type = $field_schema['type'];
// Add additional information to the schema with the data definition.
$field_schema += $this->typedConfigManager->getDefinition($data_type, FALSE);
$definition_class = $field_schema['definition_class'];
if (is_subclass_of($definition_class, MapDataDefinition::class)) {
$definition = call_user_func([$definition_class, 'createFromDataType'], $data_type)
->setTypedDataManager($this->typedDataManager);
assert($definition instanceof MapDataDefinition);
foreach ($field_schema['mapping'] as $name => $item_definition) {
$item_definition = $this->createDataDefinition($item_definition);
$definition->setPropertyDefinition($name, $item_definition);
}
return $definition;
}
$is_sequence = FALSE;
if (is_subclass_of($definition_class, ListDataDefinitionInterface::class)) {
$is_sequence = TRUE;
$data_type = $field_schema['sequence']['type'];
}
if ($this->typedDataManager->hasDefinition($data_type)) {
return $is_sequence
? $this->typedDataManager->createListDataDefinition($data_type)
: $this->typedDataManager->createDataDefinition($data_type);
}
// We tried our best. There is some information that we cannot obtain from a
//static perspective.
$data_definition = DataDefinition::createFromDataType('undefined')
->setTypedDataManager($this->typedDataManager);
if ($is_sequence) {
// Construct the sequence of 'undefined' manually.
$data_definition = ListDataDefinition::createFromDataType('sequence')
->setTypedDataManager($this->typedDataManager)
->setItemDefinition($data_definition);
}
return $data_definition;
}
}