clean install

This commit is contained in:
2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 changed files with 3555714 additions and 0 deletions

View File

@@ -0,0 +1,51 @@
<?php
namespace Drupal\serialization\Encoder;
use Symfony\Component\Serializer\Encoder\JsonDecode;
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\Encoder\JsonEncoder as BaseJsonEncoder;
/**
* Adds 'ajax' to the supported content types of the JSON encoder.
*
* @internal
* This encoder should not be used directly. Rather, use the `serializer`
* service.
*/
class JsonEncoder extends BaseJsonEncoder {
/**
* The formats that this Encoder supports.
*
* @var array
*/
protected static $format = ['json', 'ajax'];
/**
* {@inheritdoc}
*/
public function __construct(?JsonEncode $encodingImpl = NULL, ?JsonDecode $decodingImpl = NULL) {
// Encode <, >, ', &, and " for RFC4627-compliant JSON, which may also be
// embedded into HTML.
// @see \Symfony\Component\HttpFoundation\JsonResponse
$json_encoding_options = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT;
$this->encodingImpl = $encodingImpl ?: new JsonEncode([JsonEncode::OPTIONS => $json_encoding_options]);
$this->decodingImpl = $decodingImpl ?: new JsonDecode([JsonDecode::ASSOCIATIVE => TRUE]);
}
/**
* {@inheritdoc}
*/
public function supportsEncoding(string $format, array $context = []): bool {
return in_array($format, static::$format);
}
/**
* {@inheritdoc}
*/
public function supportsDecoding(string $format, array $context = []): bool {
return in_array($format, static::$format);
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace Drupal\serialization\Encoder;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
use Symfony\Component\Serializer\Encoder\DecoderInterface;
use Symfony\Component\Serializer\Encoder\XmlEncoder as BaseXmlEncoder;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerAwareTrait;
/**
* Adds XML support for serializer.
*
* This acts as a wrapper class for Symfony's XmlEncoder so that it is not
* implementing NormalizationAwareInterface, and can be normalized externally.
*
* @internal
* This encoder should not be used directly. Rather, use the `serializer`
* service.
*/
class XmlEncoder implements SerializerAwareInterface, EncoderInterface, DecoderInterface {
use SerializerAwareTrait;
/**
* The formats that this Encoder supports.
*
* @var array
*/
protected static $format = ['xml'];
/**
* An instance of the Symfony XmlEncoder to perform the actual encoding.
*
* @var \Symfony\Component\Serializer\Encoder\XmlEncoder
*/
protected $baseEncoder;
/**
* Gets the base encoder instance.
*
* @return \Symfony\Component\Serializer\Encoder\XmlEncoder
* The base encoder.
*/
public function getBaseEncoder() {
if (!isset($this->baseEncoder)) {
$this->baseEncoder = new BaseXmlEncoder();
$this->baseEncoder->setSerializer($this->serializer);
}
return $this->baseEncoder;
}
/**
* Sets the base encoder instance.
*
* @param \Symfony\Component\Serializer\Encoder\XmlEncoder $encoder
* The XML encoder.
*/
public function setBaseEncoder($encoder) {
$this->baseEncoder = $encoder;
}
/**
* {@inheritdoc}
*/
public function encode($data, $format, array $context = []): string {
return $this->getBaseEncoder()->encode($data, $format, $context);
}
/**
* {@inheritdoc}
*/
public function supportsEncoding(string $format, array $context = []): bool {
return in_array($format, static::$format);
}
/**
* {@inheritdoc}
*/
public function decode($data, $format, array $context = []): mixed {
return $this->getBaseEncoder()->decode($data, $format, $context);
}
/**
* {@inheritdoc}
*/
public function supportsDecoding(string $format, array $context = []): bool {
return in_array($format, static::$format);
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Drupal\serialization\EntityResolver;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Resolver delegating the entity resolution to a chain of resolvers.
*/
class ChainEntityResolver implements ChainEntityResolverInterface {
/**
* The concrete resolvers.
*
* @var \Drupal\serialization\EntityResolver\EntityResolverInterface[]
*/
protected $resolvers = [];
/**
* Constructs a ChainEntityResolver object.
*
* @param \Drupal\serialization\EntityResolver\EntityResolverInterface[] $resolvers
* The array of concrete resolvers.
*/
public function __construct(array $resolvers = []) {
$this->resolvers = $resolvers;
}
/**
* {@inheritdoc}
*/
public function addResolver(EntityResolverInterface $resolver) {
$this->resolvers[] = $resolver;
}
/**
* {@inheritdoc}
*/
public function resolve(NormalizerInterface $normalizer, $data, $entity_type) {
foreach ($this->resolvers as $resolver) {
$resolved = $resolver->resolve($normalizer, $data, $entity_type);
if (isset($resolved)) {
return $resolved;
}
}
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Drupal\serialization\EntityResolver;
/**
* An interface for delegating an entity resolution to a chain of resolvers.
*/
interface ChainEntityResolverInterface extends EntityResolverInterface {
/**
* Adds an entity resolver.
*
* @param \Drupal\serialization\EntityResolver\EntityResolverInterface $resolver
* The entity resolver to add.
*/
public function addResolver(EntityResolverInterface $resolver);
}

View File

@@ -0,0 +1,38 @@
<?php
namespace Drupal\serialization\EntityResolver;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
interface EntityResolverInterface {
/**
* Returns the local ID of an entity referenced by serialized data.
*
* Drupal entities are loaded by and internally referenced by a local ID.
* Because different websites can use the same local ID to refer to different
* entities (e.g., node "1" can be a different node on foo.com and bar.com, or
* on example.com and staging.example.com), it is generally unsuitable for use
* in hypermedia data exchanges. Instead, UUIDs, URIs, or other globally
* unique IDs are preferred.
*
* This function takes a $data array representing partially deserialized data
* for an entity reference, and resolves it to a local entity ID. For example,
* depending on the data specification being used, $data might contain a
* 'uuid' key, a 'uri' key, a 'href' key, or some other data identifying the
* entity, and it is up to the implementor of this interface to resolve that
* appropriately for the specification being used.
*
* @param \Symfony\Component\Serializer\Normalizer\NormalizerInterface $normalizer
* The Normalizer which is handling the data.
* @param array $data
* The data passed into the calling Normalizer.
* @param string $entity_type
* The type of entity being resolved; e.g., 'node' or 'user'.
*
* @return string|null
* Returns the local entity ID, if found. Otherwise, returns NULL.
*/
public function resolve(NormalizerInterface $normalizer, $data, $entity_type);
}

View File

@@ -0,0 +1,22 @@
<?php
namespace Drupal\serialization\EntityResolver;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Resolves entities from data that contains an entity target ID.
*/
class TargetIdResolver implements EntityResolverInterface {
/**
* {@inheritdoc}
*/
public function resolve(NormalizerInterface $normalizer, $data, $entity_type) {
if (isset($data['target_id'])) {
return $data['target_id'];
}
return NULL;
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Drupal\serialization\EntityResolver;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Interface for extracting UUID from entity reference data when denormalizing.
*/
interface UuidReferenceInterface extends NormalizerInterface {
/**
* Get the uuid from the data array.
*
* @param array $data
* The data, as was passed into the Normalizer.
*
* @return string
* A UUID.
*/
public function getUuid($data);
}

View File

@@ -0,0 +1,45 @@
<?php
namespace Drupal\serialization\EntityResolver;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Resolves entities from data that contains an entity UUID.
*/
class UuidResolver implements EntityResolverInterface {
/**
* The entity repository.
*
* @var \Drupal\Core\Entity\EntityRepositoryInterface
*/
protected $entityRepository;
/**
* Constructs a UuidResolver object.
*
* @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
* The entity repository.
*/
public function __construct(EntityRepositoryInterface $entity_repository) {
$this->entityRepository = $entity_repository;
}
/**
* {@inheritdoc}
*/
public function resolve(NormalizerInterface $normalizer, $data, $entity_type) {
// The normalizer is what knows the specification of the data being
// deserialized. If it can return a UUID from that data, and if there's an
// entity with that UUID, then return its ID.
if (($normalizer instanceof UuidReferenceInterface) && ($uuid = $normalizer->getUuid($data))) {
if ($entity = $this->entityRepository->loadEntityByUuid($entity_type, $uuid)) {
return $entity->id();
}
}
return NULL;
}
}

View File

@@ -0,0 +1,95 @@
<?php
namespace Drupal\serialization\EventSubscriber;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Cache\CacheableResponse;
use Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Serializer\SerializerInterface;
/**
* Handles default error responses in serialization formats.
*/
class DefaultExceptionSubscriber extends HttpExceptionSubscriberBase {
/**
* The serializer.
*
* @var \Symfony\Component\Serializer\Serializer
*/
protected $serializer;
/**
* The available serialization formats.
*
* @var array
*/
protected $serializerFormats = [];
/**
* DefaultExceptionSubscriber constructor.
*
* @param \Symfony\Component\Serializer\SerializerInterface $serializer
* The serializer service.
* @param array $serializer_formats
* The available serialization formats.
*/
public function __construct(SerializerInterface $serializer, array $serializer_formats) {
$this->serializer = $serializer;
$this->serializerFormats = $serializer_formats;
}
/**
* {@inheritdoc}
*/
protected function getHandledFormats() {
return $this->serializerFormats;
}
/**
* {@inheritdoc}
*/
protected static function getPriority() {
// This will fire after the most common HTML handler, since HTML requests
// are still more common than HTTP requests. But it has a lower priority
// than \Drupal\Core\EventSubscriber\ExceptionJsonSubscriber::on4xx(), so
// that this also handles the 'json' format. Then all serialization formats
// (::getHandledFormats()) are handled by this exception subscriber, which
// results in better consistency.
return -70;
}
/**
* Handles all 4xx errors for all serialization failures.
*
* @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event
* The event to process.
*/
public function on4xx(ExceptionEvent $event) {
/** @var \Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $exception */
$exception = $event->getThrowable();
$request = $event->getRequest();
$format = $request->getRequestFormat();
$content = ['message' => $exception->getMessage()];
$encoded_content = $this->serializer->serialize($content, $format);
$headers = $exception->getHeaders();
// Add the MIME type from the request to send back in the header.
$headers['Content-Type'] = $request->getMimeType($format);
// If the exception is cacheable, generate a cacheable response.
if ($exception instanceof CacheableDependencyInterface) {
$response = new CacheableResponse($encoded_content, $exception->getStatusCode(), $headers);
$response->addCacheableDependency($exception);
}
else {
$response = new Response($encoded_content, $exception->getStatusCode(), $headers);
}
$event->setResponse($response);
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace Drupal\serialization\EventSubscriber;
use Drupal\Core\Routing\RouteBuildEvent;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Alters user authentication routes to support additional serialization formats.
*/
class UserRouteAlterSubscriber implements EventSubscriberInterface {
/**
* The available serialization formats.
*
* @var array
*/
protected $serializerFormats = [];
/**
* UserRouteAlterSubscriber constructor.
*
* @param array $serializer_formats
* The available serializer formats.
*/
public function __construct(array $serializer_formats) {
$this->serializerFormats = $serializer_formats;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events[RoutingEvents::ALTER][] = 'onRoutingAlterAddFormats';
return $events;
}
/**
* Adds supported formats to the user authentication HTTP routes.
*
* @param \Drupal\Core\Routing\RouteBuildEvent $event
* The event to process.
*/
public function onRoutingAlterAddFormats(RouteBuildEvent $event) {
$route_names = [
'user.login_status.http',
'user.login.http',
'user.logout.http',
'user.pass.http',
];
$routes = $event->getRouteCollection();
foreach ($route_names as $route_name) {
if (($route = $routes->get($route_name)) && $route->hasRequirement('_format')) {
$formats = explode('|', $route->getRequirement('_format'));
$formats = array_unique(array_merge($formats, $this->serializerFormats));
$route->setRequirement('_format', implode('|', $formats));
}
}
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Drupal\serialization\Normalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Defines the interface for normalizers producing cacheable normalizations.
*
* @see cache
*/
interface CacheableNormalizerInterface extends NormalizerInterface {
/**
* Name of key for bubbling cacheability metadata via serialization context.
*
* @see \Symfony\Component\Serializer\Normalizer\NormalizerInterface::normalize()
* @see \Symfony\Component\Serializer\SerializerInterface::serialize()
* @see \Drupal\rest\EventSubscriber\ResourceResponseSubscriber::renderResponseBody()
*/
const SERIALIZATION_CONTEXT_CACHEABILITY = 'cacheability';
}

View File

@@ -0,0 +1,60 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\TypedData\ComplexDataInterface;
use Drupal\Core\TypedData\TypedDataInternalPropertiesHelper;
/**
* Converts the Drupal entity object structures to a normalized array.
*
* This is the default Normalizer for entities. All formats that have Encoders
* registered with the Serializer in the DIC will be normalized with this
* class unless another Normalizer is registered which supersedes it. If a
* module wants to use format-specific or class-specific normalization, then
* that module can register a new Normalizer and give it a higher priority than
* this one.
*/
class ComplexDataNormalizer extends NormalizerBase {
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
$attributes = [];
// $object will not always match getSupportedTypes().
// @see \Drupal\serialization\Normalizer\EntityNormalizer
// Other normalizers that extend this class may only provide $object that
// implements \Traversable.
if ($object instanceof ComplexDataInterface) {
// If there are no properties to normalize, just normalize the value.
$object = !empty($object->getProperties(TRUE))
? TypedDataInternalPropertiesHelper::getNonInternalProperties($object)
: $object->getValue();
}
/** @var \Drupal\Core\TypedData\TypedDataInterface $property */
foreach ($object as $name => $property) {
$attributes[$name] = $this->serializer->normalize($property, $format, $context);
}
return $attributes;
}
/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool {
@trigger_error(__METHOD__ . '() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use getSupportedTypes() instead. See https://www.drupal.org/node/3359695', E_USER_DEPRECATED);
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
ComplexDataInterface::class => TRUE,
];
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
/**
* Normalizes/denormalizes Drupal config entity objects into an array structure.
*/
class ConfigEntityNormalizer extends EntityNormalizer {
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
return static::getDataWithoutInternals($object->toArray());
}
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = NULL, array $context = []): mixed {
return parent::denormalize(static::getDataWithoutInternals($data), $class, $format, $context);
}
/**
* Gets the given data without the internal implementation details.
*
* @param array $data
* The data that is either currently or about to be stored in configuration.
*
* @return array
* The same data, but without internals. Currently, that is only the '_core'
* key, which is reserved by Drupal core to handle complex edge cases
* correctly. Data in the '_core' key is irrelevant to clients reading
* configuration, and is not allowed to be set by clients writing
* configuration: it is for Drupal core only, and managed by Drupal core.
*
* @see https://www.drupal.org/node/2653358
*/
protected static function getDataWithoutInternals(array $data) {
return array_diff_key($data, ['_core' => TRUE]);
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
ConfigEntityInterface::class => TRUE,
];
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\TypedData\TypedDataInternalPropertiesHelper;
/**
* Normalizes/denormalizes Drupal content entities into an array structure.
*/
class ContentEntityNormalizer extends EntityNormalizer {
/**
* {@inheritdoc}
*/
public function normalize($entity, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
$context += [
'account' => NULL,
];
$attributes = [];
/** @var \Drupal\Core\Entity\Entity $entity */
foreach (TypedDataInternalPropertiesHelper::getNonInternalProperties($entity->getTypedData()) as $name => $field_items) {
if ($field_items->access('view', $context['account'])) {
$attributes[$name] = $this->serializer->normalize($field_items, $format, $context);
}
}
return $attributes;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
ContentEntityInterface::class => TRUE,
];
}
}

View File

@@ -0,0 +1,94 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\TypedData\Plugin\DataType\DateTimeIso8601;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItem;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
/**
* Converts values for the DateTimeIso8601 data type to RFC3339.
*
* @internal
*/
class DateTimeIso8601Normalizer extends DateTimeNormalizer {
/**
* {@inheritdoc}
*/
protected $allowedFormats = [
'RFC 3339' => \DateTime::RFC3339,
'ISO 8601' => \DateTime::ISO8601,
// @todo Remove this in https://www.drupal.org/project/drupal/issues/2958416.
// RFC3339 only covers combined date and time representations. For date-only
// representations, we need to use ISO 8601. There isn't a constant on the
// \DateTime class that we can use, so we have to hardcode the format.
// @see https://en.wikipedia.org/wiki/ISO_8601#Calendar_dates
// @see \Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface::DATE_STORAGE_FORMAT
'date-only' => 'Y-m-d',
];
/**
* {@inheritdoc}
*/
public function normalize($datetime, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
assert($datetime instanceof DateTimeIso8601);
$field_item = $datetime->getParent();
// @todo Remove this in https://www.drupal.org/project/drupal/issues/2958416.
if ($field_item instanceof DateTimeItem && $field_item->getFieldDefinition()->getFieldStorageDefinition()->getSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE) {
$drupal_date_time = $datetime->getDateTime();
if ($drupal_date_time === NULL) {
return $drupal_date_time;
}
return $drupal_date_time->format($this->allowedFormats['date-only']);
}
return parent::normalize($datetime, $format, $context);
}
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = NULL, array $context = []): mixed {
// @todo Move the date-only handling out of here in https://www.drupal.org/project/drupal/issues/2958416.
if (isset($context['target_instance'])) {
$field_definition = $context['target_instance']->getFieldDefinition();
}
elseif (isset($context['field_definition'])) {
$field_definition = $context['field_definition'];
}
else {
throw new InvalidArgumentException('$context[\'target_instance\'] or $context[\'field_definition\'] must be set to denormalize with the DateTimeIso8601Normalizer');
}
$datetime_type = $field_definition->getSetting('datetime_type');
$is_date_only = $datetime_type === DateTimeItem::DATETIME_TYPE_DATE;
if ($is_date_only) {
$context['datetime_allowed_formats'] = array_intersect_key($this->allowedFormats, ['date-only' => TRUE]);
$datetime = parent::denormalize($data, $class, $format, $context);
if (!$datetime instanceof \DateTime) {
return $datetime;
}
return $datetime->format(DateTimeItemInterface::DATE_STORAGE_FORMAT);
}
$context['datetime_allowed_formats'] = array_diff_key($this->allowedFormats, ['date-only' => TRUE]);
$datetime = parent::denormalize($data, $class, $format, $context);
if (!$datetime instanceof \DateTime) {
return $datetime;
}
$datetime->setTimezone(new \DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE));
return $datetime->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
DateTimeIso8601::class => TRUE,
];
}
}

View File

@@ -0,0 +1,131 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\TypedData\Type\DateTimeInterface;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* Converts values for datetime objects to RFC3339 and from common formats.
*
* @internal
*/
class DateTimeNormalizer extends NormalizerBase implements DenormalizerInterface {
/**
* Allowed datetime formats for the denormalizer.
*
* The list is chosen to be unambiguous and language neutral, but also common
* for data interchange.
*
* @var string[]
*
* @see http://php.net/manual/en/datetime.createfromformat.php
*/
protected $allowedFormats = [
'RFC 3339' => \DateTime::RFC3339,
'ISO 8601' => \DateTime::ISO8601,
];
/**
* The system's date configuration.
*
* @var \Drupal\Core\Config\ImmutableConfig
*/
protected $systemDateConfig;
/**
* Constructs a new DateTimeNormalizer instance.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* A config factory for retrieving required config objects.
*/
public function __construct(ConfigFactoryInterface $config_factory) {
$this->systemDateConfig = $config_factory->get('system.date');
}
/**
* {@inheritdoc}
*/
public function normalize($datetime, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
assert($datetime instanceof DateTimeInterface);
$drupal_date_time = $datetime->getDateTime();
if ($drupal_date_time === NULL) {
return $drupal_date_time;
}
return $drupal_date_time
// Set an explicit timezone. Otherwise, timestamps may end up being
// normalized using the user's preferred timezone. Which would result in
// many variations and complex caching.
->setTimezone($this->getNormalizationTimezone())
->format(\DateTime::RFC3339);
}
/**
* Gets the timezone to be used during normalization.
*
* @see ::normalize
* @see \Drupal\Core\Datetime\DrupalDateTime::prepareTimezone()
*
* @return \DateTimeZone
* The timezone to use.
*/
protected function getNormalizationTimezone() {
$default_site_timezone = $this->systemDateConfig->get('timezone.default');
return new \DateTimeZone($default_site_timezone);
}
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = NULL, array $context = []): mixed {
// This only knows how to denormalize datetime strings and timestamps. If
// something else is received, let validation constraints handle this.
if (!is_string($data) && !is_numeric($data)) {
return $data;
}
// Loop through the allowed formats and create a \DateTime from the
// input data if it matches the defined pattern. Since the formats are
// unambiguous (i.e., they reference an absolute time with a defined time
// zone), only one will ever match.
$allowed_formats = $context['datetime_allowed_formats'] ?? $this->allowedFormats;
foreach ($allowed_formats as $format) {
$date = \DateTime::createFromFormat($format, $data);
$errors = \DateTime::getLastErrors();
if ($date !== FALSE && empty($errors['errors']) && empty($errors['warnings'])) {
return $date;
}
}
$format_strings = [];
foreach ($allowed_formats as $label => $format) {
$format_strings[] = "\"$format\" ($label)";
}
$formats = implode(', ', $format_strings);
throw new UnexpectedValueException(sprintf('The specified date "%s" is not in an accepted format: %s.', $data, $formats));
}
/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool {
@trigger_error(__METHOD__ . '() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use getSupportedTypes() instead. See https://www.drupal.org/node/3359695', E_USER_DEPRECATED);
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
DateTimeInterface::class => TRUE,
];
}
}

View File

@@ -0,0 +1,82 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityTypeRepositoryInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* Normalizes/denormalizes Drupal entity objects into an array structure.
*/
class EntityNormalizer extends ComplexDataNormalizer implements DenormalizerInterface {
use FieldableEntityNormalizerTrait;
/**
* Constructs an EntityNormalizer object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\Core\Entity\EntityTypeRepositoryInterface $entity_type_repository
* The entity type repository.
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
* The entity field manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityTypeRepositoryInterface $entity_type_repository, EntityFieldManagerInterface $entity_field_manager) {
$this->entityTypeManager = $entity_type_manager;
$this->entityTypeRepository = $entity_type_repository;
$this->entityFieldManager = $entity_field_manager;
}
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = NULL, array $context = []): mixed {
$entity_type_id = $this->determineEntityTypeId($class, $context);
$entity_type_definition = $this->getEntityTypeDefinition($entity_type_id);
// The bundle property will be required to denormalize a bundleable
// fieldable entity.
if ($entity_type_definition->entityClassImplements(FieldableEntityInterface::class)) {
// Extract bundle data to pass into entity creation if the entity type uses
// bundles.
if ($entity_type_definition->hasKey('bundle')) {
// Get an array containing the bundle only. This also remove the bundle
// key from the $data array.
$create_params = $this->extractBundleData($data, $entity_type_definition);
}
else {
$create_params = [];
}
// Create the entity from bundle data only, then apply field values after.
$entity = $this->entityTypeManager->getStorage($entity_type_id)->create($create_params);
$this->denormalizeFieldData($data, $entity, $format, $context);
}
else {
// Create the entity from all data.
$entity = $this->entityTypeManager->getStorage($entity_type_id)->create($data);
}
// Pass the names of the fields whose values can be merged.
// @todo https://www.drupal.org/node/2456257 remove this.
$entity->_restSubmittedFields = array_keys($data);
return $entity;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
EntityInterface::class => TRUE,
];
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\file\FileInterface;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
/**
* Adds the file URI to embedded file entities.
*/
class EntityReferenceFieldItemNormalizer extends FieldItemNormalizer {
use EntityReferenceFieldItemNormalizerTrait;
/**
* The entity repository.
*
* @var \Drupal\Core\Entity\EntityRepositoryInterface
*/
protected $entityRepository;
/**
* Constructs an EntityReferenceFieldItemNormalizer object.
*
* @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
* The entity repository.
*/
public function __construct(EntityRepositoryInterface $entity_repository) {
$this->entityRepository = $entity_repository;
}
/**
* {@inheritdoc}
*/
public function normalize($field_item, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
$values = parent::normalize($field_item, $format, $context);
$this->normalizeRootReferenceValue($values, $field_item);
/** @var \Drupal\Core\Entity\EntityInterface $entity */
if ($entity = $field_item->get('entity')->getValue()) {
$values['target_type'] = $entity->getEntityTypeId();
// Add the target entity UUID to the normalized output values.
$values['target_uuid'] = $entity->uuid();
// Add a 'url' value if there is a reference and a canonical URL. Hard
// code 'canonical' here as config entities override the default $rel
// parameter value to 'edit-form.
if ($entity->hasLinkTemplate('canonical') && !$entity->isNew() && $url = $entity->toUrl('canonical')->toString(TRUE)) {
$this->addCacheableDependency($context, $url);
$values['url'] = $url->getGeneratedUrl();
}
// @todo Remove in https://www.drupal.org/project/drupal/issues/2925520
elseif ($entity instanceof FileInterface) {
$values['url'] = $entity->createFileUrl(FALSE);
}
}
return $values;
}
/**
* {@inheritdoc}
*/
protected function constructValue($data, $context) {
if (isset($data['target_uuid'])) {
/** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $field_item */
$field_item = $context['target_instance'];
if (empty($data['target_uuid'])) {
throw new InvalidArgumentException(sprintf('If provided "target_uuid" cannot be empty for field "%s".', $field_item->getName()));
}
$target_type = $field_item->getFieldDefinition()->getSetting('target_type');
if (!empty($data['target_type']) && $target_type !== $data['target_type']) {
throw new UnexpectedValueException(sprintf('The field "%s" property "target_type" must be set to "%s" or omitted.', $field_item->getFieldDefinition()->getName(), $target_type));
}
if ($entity = $this->entityRepository->loadEntityByUuid($target_type, $data['target_uuid'])) {
return ['target_id' => $entity->id()] + array_intersect_key($data, $field_item->getProperties());
}
else {
// Unable to load entity by uuid.
throw new InvalidArgumentException(sprintf('No "%s" entity found with UUID "%s" for field "%s".', $data['target_type'], $data['target_uuid'], $field_item->getName()));
}
}
return parent::constructValue($data, $context);
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
EntityReferenceItem::class => TRUE,
];
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
/**
* Converts empty reference values for entity reference items.
*/
trait EntityReferenceFieldItemNormalizerTrait {
protected function normalizeRootReferenceValue(&$values, EntityReferenceItem $field_item) {
// @todo Generalize for all tree-structured entity types.
if ($this->fieldItemReferencesTaxonomyTerm($field_item) && empty($values['target_id'])) {
$values['target_id'] = NULL;
}
}
/**
* Determines if a field item references a taxonomy term.
*
* @param \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $field_item
* The entity reference item.
*
* @return bool
*/
protected function fieldItemReferencesTaxonomyTerm(EntityReferenceItem $field_item) {
return $field_item->getFieldDefinition()->getSetting('target_type') === 'taxonomy_term';
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Field\FieldItemInterface;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* Denormalizes field item object structure by updating the entity field values.
*/
class FieldItemNormalizer extends ComplexDataNormalizer implements DenormalizerInterface {
use FieldableEntityNormalizerTrait;
use SerializedColumnNormalizerTrait;
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = NULL, array $context = []): mixed {
if (!isset($context['target_instance'])) {
throw new InvalidArgumentException('$context[\'target_instance\'] must be set to denormalize with the FieldItemNormalizer');
}
if ($context['target_instance']->getParent() == NULL) {
throw new InvalidArgumentException('The field item passed in via $context[\'target_instance\'] must have a parent set.');
}
/** @var \Drupal\Core\Field\FieldItemInterface $field_item */
$field_item = $context['target_instance'];
$this->checkForSerializedStrings($data, $class, $field_item);
$field_item->setValue($this->constructValue($data, $context));
return $field_item;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
FieldItemInterface::class => TRUE,
];
}
}

View File

@@ -0,0 +1,61 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Field\FieldItemListInterface;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* Denormalizes data to Drupal field values.
*
* This class simply calls denormalize() on the individual FieldItems. The
* FieldItem normalizers are responsible for setting the field values for each
* item.
*
* @see \Drupal\serialization\Normalizer\FieldItemNormalizer.
*/
class FieldNormalizer extends ListNormalizer implements DenormalizerInterface {
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = NULL, array $context = []): mixed {
if (!isset($context['target_instance'])) {
throw new InvalidArgumentException('$context[\'target_instance\'] must be set to denormalize with the FieldNormalizer');
}
if ($context['target_instance']->getParent() == NULL) {
throw new InvalidArgumentException('The field passed in via $context[\'target_instance\'] must have a parent set.');
}
/** @var \Drupal\Core\Field\FieldItemListInterface $items */
$items = $context['target_instance'];
$item_class = $items->getItemDefinition()->getClass();
if (!is_array($data)) {
throw new UnexpectedValueException(sprintf('Field values for "%s" must use an array structure', $items->getName()));
}
foreach ($data as $item_data) {
// Create a new item and pass it as the target for the unserialization of
// $item_data. All items in field should have removed before this method
// was called.
// @see \Drupal\serialization\Normalizer\ContentEntityNormalizer::denormalize().
$context['target_instance'] = $items->appendItem();
$this->serializer->denormalize($item_data, $item_class, $format, $context);
}
return $items;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
FieldItemListInterface::class => TRUE,
];
}
}

View File

@@ -0,0 +1,255 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\TypedData\FieldItemDataDefinitionInterface;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
/**
* A trait for providing fieldable entity normalization/denormalization methods.
*
* @todo Move this into a FieldableEntityNormalizer in Drupal 9. This is a trait
* used in \Drupal\serialization\Normalizer\EntityNormalizer to maintain BC.
* @see https://www.drupal.org/node/2834734
*/
trait FieldableEntityNormalizerTrait {
/**
* The entity field manager.
*
* @var \Drupal\Core\Entity\EntityFieldManagerInterface
*/
protected $entityFieldManager;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The entity type repository.
*
* @var \Drupal\Core\Entity\EntityTypeRepositoryInterface
*/
protected $entityTypeRepository;
/**
* Determines the entity type ID to denormalize as.
*
* @param string $class
* The entity type class to be denormalized to.
* @param array $context
* The serialization context data.
*
* @return string
* The entity type ID.
*/
protected function determineEntityTypeId($class, $context) {
// Get the entity type ID while letting context override the $class param.
return !empty($context['entity_type']) ? $context['entity_type'] : $this->getEntityTypeRepository()->getEntityTypeFromClass($class);
}
/**
* Gets the entity type definition.
*
* @param string $entity_type_id
* The entity type ID to load the definition for.
*
* @return \Drupal\Core\Entity\EntityTypeInterface
* The loaded entity type definition.
*
* @throws \Symfony\Component\Serializer\Exception\UnexpectedValueException
*/
protected function getEntityTypeDefinition($entity_type_id) {
/** @var \Drupal\Core\Entity\EntityTypeInterface $entity_type_definition */
// Get the entity type definition.
$entity_type_definition = $this->getEntityTypeManager()->getDefinition($entity_type_id, FALSE);
// Don't try to create an entity without an entity type id.
if (!$entity_type_definition) {
throw new UnexpectedValueException(sprintf('The specified entity type "%s" does not exist. A valid entity type is required for denormalization', $entity_type_id));
}
return $entity_type_definition;
}
/**
* Denormalizes the bundle property so entity creation can use it.
*
* @param array $data
* The data being denormalized. The bundle information will be removed.
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type_definition
* The entity type definition.
*
* @throws \Symfony\Component\Serializer\Exception\UnexpectedValueException
* If the bundle value is invalid or the bundle type is ineligible.
*
* @return array
* An array containing a single $bundle_key => $bundle_value pair.
*/
protected function extractBundleData(array &$data, EntityTypeInterface $entity_type_definition) {
$bundle_key = $entity_type_definition->getKey('bundle');
// Get the base field definitions for this entity type.
$base_field_definitions = $this->getEntityFieldManager()->getBaseFieldDefinitions($entity_type_definition->id());
// Get the ID key from the base field definition for the bundle key or
// default to 'value'.
$key_id = isset($base_field_definitions[$bundle_key]) ? $base_field_definitions[$bundle_key]->getFieldStorageDefinition()->getMainPropertyName() : 'value';
// Normalize the bundle if it is not explicitly set.
$bundle_value = $data[$bundle_key][0][$key_id] ?? ($data[$bundle_key] ?? NULL);
// Unset the bundle from the data.
unset($data[$bundle_key]);
// Get the bundle entity type from the entity type definition.
$bundle_type_id = $entity_type_definition->getBundleEntityType();
$bundle_types = $bundle_type_id ? $this->getEntityTypeManager()->getStorage($bundle_type_id)->getQuery()->accessCheck(TRUE)->execute() : [];
// Make sure a bundle has been provided.
if (!is_string($bundle_value)) {
throw new UnexpectedValueException(sprintf('Could not determine entity type bundle: "%s" field is missing.', $bundle_key));
}
// Make sure the submitted bundle is a valid bundle for the entity type.
if ($bundle_types && !in_array($bundle_value, $bundle_types)) {
throw new UnexpectedValueException(sprintf('"%s" is not a valid bundle type for denormalization.', $bundle_value));
}
return [$bundle_key => $bundle_value];
}
/**
* Denormalizes entity data by denormalizing each field individually.
*
* @param array $data
* The data to denormalize.
* @param \Drupal\Core\Entity\FieldableEntityInterface $entity
* The fieldable entity to set field values for.
* @param string $format
* The serialization format.
* @param array $context
* The context data.
*/
protected function denormalizeFieldData(array $data, FieldableEntityInterface $entity, $format, array $context) {
foreach ($data as $field_name => $field_data) {
$field_item_list = $entity->get($field_name);
// Remove any values that were set as a part of entity creation (e.g
// uuid). If the incoming field data is set to an empty array, this will
// also have the effect of emptying the field in REST module.
$field_item_list->setValue([]);
$field_item_list_class = get_class($field_item_list);
if ($field_data) {
// The field instance must be passed in the context so that the field
// denormalizer can update field values for the parent entity.
$context['target_instance'] = $field_item_list;
$this->serializer->denormalize($field_data, $field_item_list_class, $format, $context);
}
}
}
/**
* Returns the entity type repository.
*
* @return \Drupal\Core\Entity\EntityTypeRepositoryInterface
* The entity type repository.
*/
protected function getEntityTypeRepository() {
return $this->entityTypeRepository;
}
/**
* Returns the entity field manager.
*
* @return \Drupal\Core\Entity\EntityFieldManagerInterface
* The entity field manager.
*/
protected function getEntityFieldManager() {
return $this->entityFieldManager;
}
/**
* Returns the entity type manager.
*
* @return \Drupal\Core\Entity\EntityTypeManagerInterface
* The entity type manager.
*/
protected function getEntityTypeManager() {
return $this->entityTypeManager;
}
/**
* Build the field item value using the incoming data.
*
* Most normalizers that extend this class can simply use this method to
* construct the denormalized value without having to override denormalize()
* and re-implementing its validation logic or its call to set the field
* value.
*
* It's recommended to not override this and instead provide a (de)normalizer
* at the DataType level.
*
* @param mixed $data
* The incoming data for this field item.
* @param array $context
* The context passed into the Normalizer.
*
* @return mixed
* The value to use in Entity::setValue().
*/
protected function constructValue($data, $context) {
$field_item = $context['target_instance'];
// Get the property definitions.
assert($field_item instanceof FieldItemInterface);
$field_definition = $field_item->getFieldDefinition();
$item_definition = $field_definition->getItemDefinition();
assert($item_definition instanceof FieldItemDataDefinitionInterface);
$property_definitions = $item_definition->getPropertyDefinitions();
$serialized_property_names = $this->getCustomSerializedPropertyNames($field_item);
$denormalize_property = function ($property_name, $property_value, $property_value_class, $context) use ($serialized_property_names) {
if ($this->serializer->supportsDenormalization($property_value, $property_value_class, NULL, $context)) {
return $this->serializer->denormalize($property_value, $property_value_class, NULL, $context);
}
else {
if (in_array($property_name, $serialized_property_names, TRUE)) {
$property_value = serialize($property_value);
}
return $property_value;
}
};
if (!is_array($data)) {
$property_value = $data;
$property_name = $item_definition->getMainPropertyName();
$property_value_class = $property_definitions[$property_name]->getClass();
return $denormalize_property($property_name, $property_value, $property_value_class, $context);
}
$data_internal = [];
if (!empty($property_definitions)) {
foreach ($property_definitions as $property_name => $property_definition) {
// Not every property is required to be sent.
if (!array_key_exists($property_name, $data)) {
continue;
}
$property_value = $data[$property_name];
$property_value_class = $property_definition->getClass();
$data_internal[$property_name] = $denormalize_property($property_name, $property_value, $property_value_class, $context);
}
}
else {
$data_internal = $data;
}
return $data_internal;
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\TypedData\ListInterface;
/**
* Converts list objects to arrays.
*
* Ordinarily, this would be handled automatically by Serializer, but since
* there is a TypedDataNormalizer and the Field class extends TypedData, any
* Field will be handled by that Normalizer instead of being traversed. This
* class ensures that TypedData classes that also implement ListInterface are
* traversed instead of simply returning getValue().
*/
class ListNormalizer extends NormalizerBase {
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
$attributes = [];
foreach ($object as $fieldItem) {
$attributes[] = $this->serializer->normalize($fieldItem, $format, $context);
}
return $attributes;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
ListInterface::class => TRUE,
];
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Component\Render\MarkupInterface;
/**
* Normalizes MarkupInterface objects into a string.
*/
class MarkupNormalizer extends NormalizerBase {
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
return (string) $object;
}
/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool {
@trigger_error(__METHOD__ . '() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use getSupportedTypes() instead. See https://www.drupal.org/node/3359695', E_USER_DEPRECATED);
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
MarkupInterface::class => TRUE,
];
}
}

View File

@@ -0,0 +1,124 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerAwareTrait;
/**
* Base class for Normalizers.
*/
abstract class NormalizerBase implements SerializerAwareInterface, CacheableNormalizerInterface {
use SerializerAwareTrait;
/**
* List of formats which supports (de-)normalization.
*
* @var string|string[]
*/
protected $format;
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, ?string $format = NULL, array $context = []): bool {
// If we aren't dealing with an object or the format is not supported return
// now.
if (!is_object($data) || !$this->checkFormat($format)) {
return FALSE;
}
if (property_exists($this, 'supportedInterfaceOrClass')) {
@trigger_error('Defining ' . static::class . '::supportedInterfaceOrClass property is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use getSupportedTypes() instead. See https://www.drupal.org/node/3359695', E_USER_DEPRECATED);
$supported = (array) $this->supportedInterfaceOrClass;
}
else {
$supported = array_keys($this->getSupportedTypes($format));
}
return (bool) array_filter($supported, function ($name) use ($data) {
return $data instanceof $name;
});
}
/**
* Implements \Symfony\Component\Serializer\Normalizer\DenormalizerInterface::supportsDenormalization()
*
* This class doesn't implement DenormalizerInterface, but most of its child
* classes do. Therefore, this method is implemented at this level to reduce
* code duplication.
*/
public function supportsDenormalization($data, string $type, ?string $format = NULL, array $context = []): bool {
// If the format is not supported return now.
if (!$this->checkFormat($format)) {
return FALSE;
}
if (property_exists($this, 'supportedInterfaceOrClass')) {
@trigger_error('Defining ' . static::class . '::supportedInterfaceOrClass property is deprecated in drupal:10.2.0 and is removed from drupal:11.0.0. Use getSupportedTypes() instead. See https://www.drupal.org/node/3359695', E_USER_DEPRECATED);
$supported = (array) $this->supportedInterfaceOrClass;
}
else {
$supported = array_keys($this->getSupportedTypes($format));
}
$subclass_check = function ($name) use ($type) {
return (class_exists($name) || interface_exists($name)) && is_subclass_of($type, $name, TRUE);
};
return in_array($type, $supported) || array_filter($supported, $subclass_check);
}
/**
* Checks if the provided format is supported by this normalizer.
*
* @param string $format
* The format to check.
*
* @return bool
* TRUE if the format is supported, FALSE otherwise. If no format is
* specified this will return TRUE.
*/
protected function checkFormat($format = NULL) {
if (!isset($format) || !isset($this->format)) {
return TRUE;
}
return in_array($format, (array) $this->format, TRUE);
}
/**
* Adds cacheability if applicable.
*
* @param array $context
* Context options for the normalizer.
* @param $data
* The data that might have cacheability information.
*/
protected function addCacheableDependency(array $context, $data) {
if ($data instanceof CacheableDependencyInterface && isset($context[static::SERIALIZATION_CONTEXT_CACHEABILITY])) {
$context[static::SERIALIZATION_CONTEXT_CACHEABILITY]->addCacheableDependency($data);
}
}
/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool {
@trigger_error(__METHOD__ . '() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use getSupportedTypes() instead. See https://www.drupal.org/node/3359695', E_USER_DEPRECATED);
return FALSE;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
'*' => FALSE,
];
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace Drupal\serialization\Normalizer;
/**
* Null normalizer.
*/
class NullNormalizer extends NormalizerBase {
/**
* The interface or class that this Normalizer supports.
*
* @var string[]
*/
protected array $supportedTypes = ['*' => FALSE];
/**
* Constructs a NullNormalizer object.
*
* @param string|array $supported_interface_of_class
* The supported interface(s) or class(es).
*/
public function __construct($supported_interface_of_class) {
$this->supportedTypes = [$supported_interface_of_class => TRUE];
}
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
return NULL;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return $this->supportedTypes;
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\TypedData\PrimitiveInterface;
/**
* Converts primitive data objects to their casted values.
*/
class PrimitiveDataNormalizer extends NormalizerBase {
use SerializedColumnNormalizerTrait;
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
// Add cacheability if applicable.
$this->addCacheableDependency($context, $object);
$parent = $object->getParent();
if ($parent instanceof FieldItemInterface && $object->getValue()) {
$serialized_property_names = $this->getCustomSerializedPropertyNames($parent);
if (in_array($object->getName(), $serialized_property_names, TRUE)) {
return unserialize($object->getValue());
}
}
// Typed data casts NULL objects to their empty variants, so for example
// the empty string ('') for string type data, or 0 for integer typed data.
// In a better world with typed data implementing algebraic data types,
// getCastedValue would return NULL, but as typed data is not aware of real
// optional values on the primitive level, we implement our own optional
// value normalization here.
return $object->getValue() === NULL ? NULL : $object->getCastedValue();
}
/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool {
@trigger_error(__METHOD__ . '() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use getSupportedTypes() instead. See https://www.drupal.org/node/3359695', E_USER_DEPRECATED);
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
PrimitiveInterface::class => TRUE,
];
}
}

View File

@@ -0,0 +1,116 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Component\Plugin\PluginInspectionInterface;
use Drupal\Core\Field\FieldItemInterface;
/**
* A trait providing methods for serialized columns.
*/
trait SerializedColumnNormalizerTrait {
/**
* Checks if there is a serialized string for a column.
*
* @param mixed $data
* The field item data to denormalize.
* @param string $class
* The expected class to instantiate.
* @param \Drupal\Core\Field\FieldItemInterface $field_item
* The field item.
*/
protected function checkForSerializedStrings($data, $class, FieldItemInterface $field_item) {
// Require specialized denormalizers for fields with 'serialize' columns.
// Note: this cannot be checked in ::supportsDenormalization() because at
// that time we only have the field item class. ::hasSerializeColumn()
// must be able to call $field_item->schema(), which requires a field
// storage definition. To determine that, the entity type and bundle
// must be known, which is contextual information that the Symfony
// serializer does not pass to ::supportsDenormalization().
if (!is_array($data)) {
$data = [$field_item->getDataDefinition()->getMainPropertyName() => $data];
}
if ($this->dataHasStringForSerializeColumn($field_item, $data)) {
$field_name = $field_item->getParent() ? $field_item->getParent()->getName() : $field_item->getName();
throw new \LogicException(sprintf('The generic FieldItemNormalizer cannot denormalize string values for "%s" properties of the "%s" field (field item class: %s).', implode('", "', $this->getSerializedPropertyNames($field_item)), $field_name, $class));
}
}
/**
* Checks if the data contains string value for serialize column.
*
* @param \Drupal\Core\Field\FieldItemInterface $field_item
* The field item.
* @param array $data
* The data being denormalized.
*
* @return bool
* TRUE if there is a string value for serialize column, otherwise FALSE.
*/
protected function dataHasStringForSerializeColumn(FieldItemInterface $field_item, array $data) {
foreach ($this->getSerializedPropertyNames($field_item) as $property_name) {
if (isset($data[$property_name]) && is_string($data[$property_name])) {
return TRUE;
}
}
return FALSE;
}
/**
* Gets the names of all serialized properties.
*
* @param \Drupal\Core\Field\FieldItemInterface $field_item
* The field item.
*
* @return string[]
* The property names for serialized properties.
*/
protected function getSerializedPropertyNames(FieldItemInterface $field_item) {
$field_storage_definition = $field_item->getFieldDefinition()->getFieldStorageDefinition();
if ($custom_property_names = $this->getCustomSerializedPropertyNames($field_item)) {
return $custom_property_names;
}
$field_storage_schema = $field_item->schema($field_storage_definition);
// If there are no columns then there are no serialized properties.
if (!isset($field_storage_schema['columns'])) {
return [];
}
$serialized_columns = array_filter($field_storage_schema['columns'], function ($column_schema) {
return isset($column_schema['serialize']) && $column_schema['serialize'] === TRUE;
});
return array_keys($serialized_columns);
}
/**
* Gets the names of all properties the plugin treats as serialized data.
*
* This allows the field storage definition or entity type to provide a
* setting for serialized properties. This can be used for fields that
* handle serialized data themselves and do not rely on the serialized schema
* flag.
*
* @param \Drupal\Core\Field\FieldItemInterface $field_item
* The field item.
*
* @return string[]
* The property names for serialized properties.
*/
protected function getCustomSerializedPropertyNames(FieldItemInterface $field_item) {
if ($field_item instanceof PluginInspectionInterface) {
$definition = $field_item->getPluginDefinition();
$serialized_fields = $field_item->getEntity()->getEntityType()->get('serialized_field_property_names');
$field_name = $field_item->getFieldDefinition()->getName();
if (is_array($serialized_fields) && isset($serialized_fields[$field_name]) && is_array($serialized_fields[$field_name])) {
return $serialized_fields[$field_name];
}
if (isset($definition['serialized_property_names']) && is_array($definition['serialized_property_names'])) {
return $definition['serialized_property_names'];
}
}
return [];
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\Field\Plugin\Field\FieldType\TimestampItem;
use Drupal\Core\TypedData\Plugin\DataType\Timestamp;
/**
* Converts values for TimestampItem to and from common formats.
*
* Overrides FieldItemNormalizer to use \Drupal\serialization\Normalizer\TimestampNormalizer
*
* Overrides FieldItemNormalizer to
* - during normalization, add the 'format' key to assist consumers
* - during denormalization, use \Drupal\serialization\Normalizer\TimestampNormalizer
*/
class TimestampItemNormalizer extends FieldItemNormalizer {
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
return parent::normalize($object, $format, $context) + [
// 'format' is not a property on Timestamp objects. This is present to
// assist consumers of this data.
'format' => \DateTime::RFC3339,
];
}
/**
* {@inheritdoc}
*/
protected function constructValue($data, $context) {
if (!empty($data['format'])) {
$context['datetime_allowed_formats'] = [$data['format']];
}
return ['value' => $this->serializer->denormalize($data['value'], Timestamp::class, NULL, $context)];
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
TimestampItem::class => TRUE,
];
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\TypedData\Plugin\DataType\Timestamp;
/**
* Converts values for the Timestamp data type to and from common formats.
*
* @internal
*
* Note that \Drupal\Core\TypedData\Plugin\DataType\Timestamp::getDateTime()
* explicitly sets a default timezone of UTC. This ensures the string
* representation generated by DateTimeNormalizer::normalize() is also in UTC.
*/
class TimestampNormalizer extends DateTimeNormalizer {
/**
* {@inheritdoc}
*/
protected $allowedFormats = [
'UNIX timestamp' => 'U',
'ISO 8601' => \DateTime::ISO8601,
'RFC 3339' => \DateTime::RFC3339,
];
/**
* {@inheritdoc}
*/
protected function getNormalizationTimezone() {
return new \DateTimeZone('UTC');
}
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = NULL, array $context = []): mixed {
$denormalized = parent::denormalize($data, $class, $format, $context);
return $denormalized->getTimestamp();
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
Timestamp::class => TRUE,
];
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace Drupal\serialization\Normalizer;
use Drupal\Core\TypedData\TypedDataInterface;
/**
* Converts typed data objects to arrays.
*/
class TypedDataNormalizer extends NormalizerBase {
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
$this->addCacheableDependency($context, $object);
$value = $object->getValue();
// Support for stringable value objects: avoid numerous custom normalizers.
if (is_object($value) && method_exists($value, '__toString')) {
$value = (string) $value;
}
return $value;
}
/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool {
@trigger_error(__METHOD__ . '() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use getSupportedTypes() instead. See https://www.drupal.org/node/3359695', E_USER_DEPRECATED);
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
TypedDataInterface::class => TRUE,
];
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Drupal\serialization;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Adds services tagged 'entity_resolver' to the Serializer.
*/
class RegisterEntityResolversCompilerPass implements CompilerPassInterface {
/**
* Adds services to the Serializer.
*
* @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
* The container to process.
*/
public function process(ContainerBuilder $container) {
$definition = $container->getDefinition('serializer.entity_resolver');
$resolvers = [];
// Retrieve registered Normalizers and Encoders from the container.
foreach ($container->findTaggedServiceIds('entity_resolver') as $id => $attributes) {
$priority = $attributes[0]['priority'] ?? 0;
$resolvers[$priority][] = new Reference($id);
}
// Add the registered concrete EntityResolvers to the ChainEntityResolver.
foreach ($this->sort($resolvers) as $resolver) {
$definition->addMethodCall('addResolver', [$resolver]);
}
}
/**
* Sorts by priority.
*
* Order services from highest priority number to lowest (reverse sorting).
*
* @param array $services
* A nested array keyed on priority number. For each priority number, the
* value is an array of Symfony\Component\DependencyInjection\Reference
* objects, each a reference to a normalizer or encoder service.
*
* @return array
* A flattened array of Reference objects from $services, ordered from high
* to low priority.
*/
protected function sort($services) {
krsort($services);
return array_merge(...$services);
}
}

View File

@@ -0,0 +1,81 @@
<?php
namespace Drupal\serialization;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Adds services tagged 'normalizer' and 'encoder' to the Serializer.
*/
class RegisterSerializationClassesCompilerPass implements CompilerPassInterface {
/**
* {@inheritdoc}
*
* phpcs:ignore Drupal.Commenting.FunctionComment.VoidReturn
* @return void
*/
public function process(ContainerBuilder $container) {
$definition = $container->getDefinition('serializer');
// Retrieve registered Normalizers and Encoders from the container.
foreach ($container->findTaggedServiceIds('normalizer') as $id => $attributes) {
// The 'serializer' service is the public API: mark normalizers private.
$container->getDefinition($id)->setPublic(FALSE);
$priority = $attributes[0]['priority'] ?? 0;
$normalizers[$priority][] = new Reference($id);
}
foreach ($container->findTaggedServiceIds('encoder') as $id => $attributes) {
// The 'serializer' service is the public API: mark encoders private.
$container->getDefinition($id)->setPublic(FALSE);
$priority = $attributes[0]['priority'] ?? 0;
$encoders[$priority][] = new Reference($id);
}
// Add the registered Normalizers and Encoders to the Serializer.
if (!empty($normalizers)) {
$definition->replaceArgument(0, $this->sort($normalizers));
}
if (!empty($encoders)) {
$definition->replaceArgument(1, $this->sort($encoders));
}
// Find all serialization formats known.
$formats = [];
$format_providers = [];
foreach ($container->findTaggedServiceIds('encoder') as $service_id => $attributes) {
$format = $attributes[0]['format'];
$formats[] = $format;
if ($provider_tag = $container->getDefinition($service_id)->getTag('_provider')) {
$format_providers[$format] = $provider_tag[0]['provider'];
}
}
$container->setParameter('serializer.formats', $formats);
$container->setParameter('serializer.format_providers', $format_providers);
}
/**
* Sorts by priority.
*
* Order services from highest priority number to lowest (reverse sorting).
*
* @param array $services
* A nested array keyed on priority number. For each priority number, the
* value is an array of Symfony\Component\DependencyInjection\Reference
* objects, each a reference to a normalizer or encoder service.
*
* @return array
* A flattened array of Reference objects from $services, ordered from high
* to low priority.
*/
protected function sort($services) {
krsort($services);
return array_merge(...$services);
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Drupal\serialization;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderInterface;
/**
* Serialization dependency injection container.
*/
class SerializationServiceProvider implements ServiceProviderInterface {
/**
* {@inheritdoc}
*/
public function register(ContainerBuilder $container) {
// Add a compiler pass for adding Normalizers and Encoders to Serializer.
$container->addCompilerPass(new RegisterSerializationClassesCompilerPass());
// Add a compiler pass for adding concrete Resolvers to chain Resolver.
$container->addCompilerPass(new RegisterEntityResolversCompilerPass());
}
}