8000 [Serializer] Allow to provide (de)normalization context in mapping by ogizanagi · Pull Request #39399 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content
8000

[Serializer] Allow to provide (de)normalization context in mapping #39399

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions src/Symfony/Component/Serializer/Annotation/Context.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Annotation;

use Symfony\Component\Serializer\Exception\InvalidArgumentException;

/**
* Annotation class for @Context().
*
* @Annotation
* @Target({"PROPERTY", "METHOD"})
*
* @author Maxime Steinhausser <maxime.steinhausser@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
final class Context
{
private $context;
private $normalizationContext;
private $denormalizationContext;
private $groups;

/**
* @throws InvalidArgumentException
*/
public function __construct(array $options = [], array $context = [], array $normalizationContext = [], array $denormalizationContext = [], array $groups = [])
{
if (!$context) {
if (!array_intersect((array_keys($options)), ['normalizationContext', 'groups', 'context', 'value', 'denormalizationContext'])) {
// gracefully supports context as first, unnamed attribute argument if it cannot be confused with Doctrine-style options
$context = $options;
} else {
// If at least one of the options match, it's likely to be Doctrine-style options. Search for the context inside:
$context = $options['value'] ?? $options['context'] ?? [];
}
}

$normalizationContext = $options['normalizationContext'] ?? $normalizationContext;
$denormalizationContext = $options['denormalizationContext'] ?? $denormalizationContext;

foreach (compact(['context', 'normalizationContext', 'denormalizationContext']) as $key => $value) {
if (!\is_array($value)) {
throw new InvalidArgumentException(sprintf('Option "%s" of annotation "%s" must be an array.', $key, static::class));
}
}

if (!$context && !$normalizationContext && !$denormalizationContext) {
throw new InvalidArgumentException(sprintf('At least one of the "context", "normalizationContext", or "denormalizationContext" options of annotation "%s" must be provided as a non-empty array.', static::class));
}

$groups = (array) ($options['groups'] ?? $groups);

foreach ($groups as $group) {
if (!\is_string($group)) {
throw new InvalidArgumentException(sprintf('Parameter "groups" of annotation "%s" must be a string or an array of strings. Got "%s".', static::class, get_debug_type($group)));
}
}

$this->context = $context;
$this->normalizationContext = $normalizationContext;
$this->denormalizationContext = $denormalizationContext;
$this->groups = $groups;
}

public function getContext(): array
{
return $this->context;
}

public function getNormalizationContext(): array
{
return $this->normalizationContext;
}

public function getDenormalizationContext(): array
{
return $this->denormalizationContext;
}

public function getGroups(): array
{
return $this->groups;
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
5.3
---

* Add the ability to provide (de)normalization context using metadata (e.g. `@Symfony\Component\Serializer\Annotation\Context`)
* deprecated `ArrayDenormalizer::setSerializer()`, call `setDenormalizer()` instead.
* added normalization formats to `UidNormalizer`

Expand Down
96 changes: 95 additions & 1 deletion src/Symfony/Component/Serializer/Mapping/AttributeMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,24 @@ class AttributeMetadata implements AttributeMetadataInterface
*/
public $ignore = false;

/**
* @var array[] Normalization contexts per group name ("*" applies to all groups)
*
* @internal This property is public in order to reduce the size of the
* class' serialized representation. Do not access it. Use
* {@link getNormalizationContexts()} instead.
*/
public $normalizationContexts = [];

/**
* @var array[] Denormalization contexts per group name ("*" applies to all groups)
Copy link
Contributor Author
@ogizanagi ogizanagi Dec 9, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using * should be fine since #33540 already relies on this. So no one should name their groups *.
Otherwise, previous version used an empty string, but we could simply opt for a distinct defaultDenormalizationContext property as well.

*
* @internal This property is public in order to reduce the size of the
* class' serialized representation. Do not access it. Use
* {@link getDenormalizationContexts()} instead.
*/
public $denormalizationContexts = [];

public function __construct(string $name)
{
$this->name = $name;
Expand Down Expand Up @@ -138,6 +156,76 @@ public function isIgnored(): bool
return $this->ignore;
}

/**
* {@inheritdoc}
*/
public function getNormalizationContexts(): array
{
return $this->normalizationContexts;
}

/**
* {@inheritdoc}
*/
public function getNormalizationContextForGroups(array $groups): array
{
$contexts = [];
foreach ($groups as $group) {
$contexts[] = $this->normalizationContexts[$group] ?? [];
}

return array_merge($this->normalizationContexts['*'] ?? [], ...$contexts);
}

/**
* {@inheritdoc}
*/
public function setNormalizationContextForGroups(array $context, array $groups = []): void
{
if (!$groups) {
$this->normalizationContexts['*'] = $context;
}

foreach ($groups as $group) {
$this->normalizationContexts[$group] = $context;
}
}

/**
* {@inheritdoc}
*/
public function getDenormalizationContexts(): array
{
return $this->denormalizationContexts;
}

/**
* {@inheritdoc}
*/
public function getDenormalizationContextForGroups(array $groups): array
{
$contexts = [];
foreach ($groups as $group) {
$contexts[] = $this->denormalizationContexts[$group] ?? [];
}

return array_merge($this->denormalizationContexts['*'] ?? [], ...$contexts);
}

/**
* {@inheritdoc}
*/
public function setDenormalizationContextForGroups(array $context, array $groups = []): void
{
if (!$groups) {
$this->denormalizationContexts['*'] = $context;
}

foreach ($groups as $group) {
$this->denormalizationContexts[$group] = $context;
}
}

/**
* {@inheritdoc}
*/
Expand All @@ -157,6 +245,12 @@ public function merge(AttributeMetadataInterface $attributeMetadata)
$this->serializedName = $attributeMetadata->getSerializedName();
}

// Overwrite only if both contexts are empty
if (!$this->normalizationContexts && !$this->denormalizationContexts) {
$this->normalizationContexts = $attributeMetadata->getNormalizationContexts();
$this->denormalizationContexts = $attributeMetadata->getDenormalizationContexts();
}

if ($ignore = $attributeMetadata->isIgnored()) {
$this->ignore = $ignore;
}
Expand All @@ -169,6 +263,6 @@ public function merge(AttributeMetadataInterface $attributeMetadata)
*/
public function __sleep()
{
return ['name', 'groups', 'maxDepth', 'serializedName', 'ignore'];
return ['name', 'groups', 'maxDepth', 'serializedName', 'ignore', 'normalizationContexts', 'denormalizationContexts'];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,34 @@ public function isIgnored(): bool;
* Merges an {@see AttributeMetadataInterface} with in the current one.
*/
public function merge(self $attributeMetadata);

/**
* Gets all the normalization contexts per group ("*" being the base context applied to all groups).
*/
public function getNormalizationContexts(): array;

/**
* Gets the computed normalization contexts for given groups.
*/
public function getNormalizationContextForGroups(array $groups): array;

/**
* Sets the normalization context for given groups.
*/
public function setNormalizationContextForGroups(array $context, array $groups = []): void;

/**
* Gets all the denormalization contexts per group ("*" being the base context applied to all groups).
*/
public function getDenormalizationContexts(): array;

/**
* Gets the computed denormalization contexts for given groups.
*/
public function getDenormalizationContextForGroups(array $groups): array;

/**
* Sets the denormalization context for given groups.
*/
public function setDenormalizationContextForGroups(array $context, array $groups = []): void;
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@
namespace Symfony\Component\Serializer\Mapping\Loader;

use Doctrine\Common\Annotations\Reader;
use Symfony\Component\Serializer\Annotation\Context;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Serializer\Annotation\Ignore;
use Symfony\Component\Serializer\Annotation\MaxDepth;
use Symfony\Component\Serializer\Annotation\SerializedName;
use Symfony\Component\Serializer\Exception\MappingException;
use Symfony\Component\Serializer\Mapping\AttributeMetadata;
use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;

Expand All @@ -36,6 +38,7 @@ class AnnotationLoader implements LoaderInterface
Ignore::class => true,
MaxDepth::class => true,
SerializedName::class => true,
Context::class => true,
];

private $reader;
Expand Down Expand Up @@ -83,6 +86,8 @@ public function loadClassMetadata(ClassMetadataInterface $classMetadata)
$attributesMetadata[$property->name]->setSerializedName($annotation->getSerializedName());
} elseif ($annotation instanceof Ignore) {
$attributesMetadata[$property->name]->setIgnore(true);
} elseif ($annotation instanceof Context) {
$this->setAttributeContextsForGroups($annotation, $attributesMetadata[$property->name]);
}

$loaded = true;
Expand Down Expand Up @@ -130,6 +135,12 @@ public function loadClassMetadata(ClassMetadataInterface $classMetadata)
$attributeMetadata->setSerializedName($annotation->getSerializedName());
} elseif ($annotation instanceof Ignore) {
$attributeMetadata->setIgnore(true);
} elseif ($annotation instanceof Context) {
if (!$accessorOrMutator) {
throw new MappingException(sprintf('Context on "%s::%s()" cannot be added. Context can only be added on methods beginning with "get", "is", "has" or "set".', $className, $method->name));
}

$this->setAttributeContextsForGroups($annotation, $attributeMetadata);
}

$loaded = true;
Expand Down Expand Up @@ -166,4 +177,20 @@ public function loadAnnotations(object $reflector): iterable
yield from $this->reader->getPropertyAnnotations($reflector);
}
}

private function setAttributeContextsForGroups(Context $annotation, AttributeMetadataInterface $attributeMetadata): void
{
if ($annotation->getContext()) {
$attributeMetadata->setNormalizationContextForGroups($annotation->getContext(), $annotation->getGroups());
$attributeMetadata->setDenormalizationContextForGroups($annotation->getContext(), $annotation->getGroups());
}

if ($annotation->getNormalizationContext()) {
$attributeMetadata->setNormalizationContextForGroups($annotation->getNormalizationContext(), $annotation->getGroups());
}

if ($annotation->getDenormalizationContext()) {
$attributeMetadata->setDenormalizationContextForGroups($annotation->getDenormalizationContext(), $annotation->getGroups());
}
}
}
44 changes: 44 additions & 0 deletions src/Symfony/Component/Serializer/Mapping/Loader/XmlFileLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,25 @@ public function loadClassMetadata(ClassMetadataInterface $classMetadata)
if (isset($attribute['ignore'])) {
$attributeMetadata->setIgnore((bool) $attribute['ignore']);
}

foreach ($attribute->context as $node) {
$groups = (array) $node->group;
$context = $this->parseContext($node->entry);
$attributeMetadata->setNormalizationContextForGroups($context, $groups);
$attributeMetadata->setDenormalizationContextForGroups($context, $groups);
}

foreach ($attribute->normalization_context as $node) {
$groups = (array) $node->group;
$context = $this->parseContext($node->entry);
$attributeMetadata->setNormalizationContextForGroups($context, $groups);
}

foreach ($attribute->denormalization_context as $node) {
$groups = (array) $node->group;
$context = $this->parseContext($node->entry);
$attributeMetadata->setDenormalizationContextForGroups($context, $groups);
}
}

if (isset($xml->{'discriminator-map'})) {
Expand Down Expand Up @@ -136,4 +155,29 @@ private function getClassesFromXml(): array

return $classes;
}

private function parseContext(\SimpleXMLElement $nodes): array
{
$context = [];

foreach ($nodes as $node) {
if (\count($node) > 0) {
if (\count($node->entry) > 0) {
$value = $this->parseContext($node->entry);
} else {
$value = [];
}
} else {
$value = XmlUtils::phpize($node);
}

if (isset($node['name'])) {
$context[(string) $node['name']] = $value;
} else {
$context[] = $value;
}
}

return $context;
}
}
Loading
0