Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Serializer] Add SerializedPath annotation to flatten nested attributes #43534

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
Oct 23, 2022
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
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ final class SerializedName
{
public function __construct(private string $serializedName)
{
if (empty($serializedName)) {
throw new InvalidArgumentException(sprintf('Parameter of annotation "%s" must be a non-empty string.', static::class));
if ('' === $serializedName) {
throw new InvalidArgumentException(sprintf('Parameter of annotation "%s" must be a non-empty string.', self::class));
}
}

Expand Down
45 changes: 45 additions & 0 deletions src/Symfony/Component/Serializer/Annotation/SerializedPath.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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\PropertyAccess\Exception\InvalidPropertyPathException;
use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;

/**
* Annotation class for @SerializedPath().
*
* @Annotation
* @NamedArgumentConstructor
* @Target({"PROPERTY", "METHOD"})
*
* @author Tobias Bönner <[email protected]>
*/
#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::TARGET_PROPERTY)]
final class SerializedPath
{
private PropertyPath $serializedPath;

public function __construct(string $serializedPath)
{
try {
$this->serializedPath = new PropertyPath($serializedPath);
} catch (InvalidPropertyPathException $pathException) {
throw new InvalidArgumentException(sprintf('Parameter of annotation "%s" must be a valid property path.', self::class));
}
}

public function getSerializedPath(): PropertyPath
{
return $this->serializedPath;
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ CHANGELOG
* Change the signature of `AttributeMetadataInterface::setSerializedName()` to `setSerializedName(?string)`
* Change the signature of `ClassMetadataInterface::setClassDiscriminatorMapping()` to `setClassDiscriminatorMapping(?ClassDiscriminatorMapping)`
* Add option YamlEncoder::YAML_INDENTATION to YamlEncoder constructor options to configure additional indentation for each level of nesting. This allows configuring indentation in the service configuration.
* Add `SerializedPath` annotation to flatten nested attributes

6.1
---
Expand Down
32 changes: 23 additions & 9 deletions src/Symfony/Component/Serializer/Mapping/AttributeMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\Component\Serializer\Mapping;

use Symfony\Component\PropertyAccess\PropertyPath;

/**
* @author Kévin Dunglas <[email protected]>
*/
Expand Down Expand Up @@ -48,6 +50,13 @@ class AttributeMetadata implements AttributeMetadataInterface
*/
public $serializedName;

/**
* @internal This property is public in order to reduce the size of the
* class' serialized representation. Do not access it. Use
* {@link getSerializedPath()} instead.
*/
public ?PropertyPath $serializedPath = null;

/**
* @var bool
*
Expand Down Expand Up @@ -121,6 +130,16 @@ public function getSerializedName(): ?string
return $this->serializedName;
}

public function setSerializedPath(PropertyPath $serializedPath = null): void
{
$this->serializedPath = $serializedPath;
}

public function getSerializedPath(): ?PropertyPath
{
return $this->serializedPath;
}

public function setIgnore(bool $ignore)
{
$this->ignore = $ignore;
Expand Down Expand Up @@ -190,14 +209,9 @@ public function merge(AttributeMetadataInterface $attributeMetadata)
}

// Overwrite only if not defined
if (null === $this->maxDepth) {
$this->maxDepth = $attributeMetadata->getMaxDepth();
}

// Overwrite only if not defined
if (null === $this->serializedName) {
$this->serializedName = $attributeMetadata->getSerializedName();
}
$this->maxDepth ??= $attributeMetadata->getMaxDepth();
$this->serializedName ??= $attributeMetadata->getSerializedName();
$this->serializedPath ??= $attributeMetadata->getSerializedPath();

// Overwrite only if both contexts are empty
if (!$this->normalizationContexts && !$this->denormalizationContexts) {
Expand All @@ -217,6 +231,6 @@ public function merge(AttributeMetadataInterface $attributeMetadata)
*/
public function __sleep(): array
{
return ['name', 'groups', 'maxDepth', 'serializedName', 'ignore', 'normalizationContexts', 'denormalizationContexts'];
return ['name', 'groups', 'maxDepth', 'serializedName', 'serializedPath', 'ignore', 'normalizationContexts', 'denormalizationContexts'];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\Component\Serializer\Mapping;

use Symfony\Component\PropertyAccess\PropertyPath;

/**
* Stores metadata needed for serializing and deserializing attributes.
*
Expand Down Expand Up @@ -59,6 +61,10 @@ public function setSerializedName(?string $serializedName);
*/
public function getSerializedName(): ?string;

public function setSerializedPath(?PropertyPath $serializedPath): void;

public function getSerializedPath(): ?PropertyPath;

/**
* Sets if this attribute must be ignored or not.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ private function generateDeclaredClassMetadata(array $classMetadatas): string
$attributeMetadata->getGroups(),
$attributeMetadata->getMaxDepth(),
$attributeMetadata->getSerializedName(),
$attributeMetadata->getSerializedPath(),
];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Symfony\Component\Serializer\Annotation\Ignore;
use Symfony\Component\Serializer\Annotation\MaxDepth;
use Symfony\Component\Serializer\Annotation\SerializedName;
use Symfony\Component\Serializer\Annotation\SerializedPath;
use Symfony\Component\Serializer\Exception\MappingException;
use Symfony\Component\Serializer\Mapping\AttributeMetadata;
use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface;
Expand All @@ -38,6 +39,7 @@ class AnnotationLoader implements LoaderInterface
Ignore::class,
MaxDepth::class,
SerializedName::class,
SerializedPath::class,
Context::class,
];

Expand Down Expand Up @@ -81,6 +83,8 @@ public function loadClassMetadata(ClassMetadataInterface $classMetadata): bool
$attributesMetadata[$property->name]->setMaxDepth($annotation->getMaxDepth());
} elseif ($annotation instanceof SerializedName) {
$attributesMetadata[$property->name]->setSerializedName($annotation->getSerializedName());
} elseif ($annotation instanceof SerializedPath) {
$attributesMetadata[$property->name]->setSerializedPath($annotation->getSerializedPath());
} elseif ($annotation instanceof Ignore) {
$attributesMetadata[$property->name]->setIgnore(true);
} elseif ($annotation instanceof Context) {
Expand Down Expand Up @@ -134,6 +138,12 @@ public function loadClassMetadata(ClassMetadataInterface $classMetadata): bool
}

$attributeMetadata->setSerializedName($annotation->getSerializedName());
} elseif ($annotation instanceof SerializedPath) {
if (!$accessorOrMutator) {
throw new MappingException(sprintf('SerializedPath on "%s::%s()" cannot be added. SerializedPath can only be added on methods beginning with "get", "is", "has" or "set".', $className, $method->name));
}

$attributeMetadata->setSerializedPath($annotation->getSerializedPath());
} elseif ($annotation instanceof Ignore) {
if (!$accessorOrMutator) {
throw new MappingException(sprintf('Ignore on "%s::%s()" cannot be added. Ignore can only be added on methods beginning with "get", "is", "has" or "set".', $className, $method->name));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
namespace Symfony\Component\Serializer\Mapping\Loader;

use Symfony\Component\Config\Util\XmlUtils;
use Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException;
use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\Serializer\Exception\MappingException;
use Symfony\Component\Serializer\Mapping\AttributeMetadata;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
Expand Down Expand Up @@ -68,6 +70,14 @@ public function loadClassMetadata(ClassMetadataInterface $classMetadata): bool
$attributeMetadata->setSerializedName((string) $attribute['serialized-name']);
}

if (isset($attribute['serialized-path'])) {
try {
$attributeMetadata->setSerializedPath(new PropertyPath((string) $attribute['serialized-path']));
} catch (InvalidPropertyPathException) {
throw new MappingException(sprintf('The "serialized-path" value must be a valid property path for the attribute "%s" of the class "%s".', $attributeName, $classMetadata->getName()));
}
}

if (isset($attribute['ignore'])) {
$attributeMetadata->setIgnore(XmlUtils::phpize($attribute['ignore']));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\Component\Serializer\Mapping\Loader;

use Symfony\Component\PropertyAccess\Exception\InvalidPropertyPathException;
use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\Serializer\Exception\MappingException;
use Symfony\Component\Serializer\Mapping\AttributeMetadata;
use Symfony\Component\Serializer\Mapping\ClassDiscriminatorMapping;
Expand Down Expand Up @@ -84,13 +86,21 @@ public function loadClassMetadata(ClassMetadataInterface $classMetadata): bool
}

if (isset($data['serialized_name'])) {
if (!\is_string($data['serialized_name']) || empty($data['serialized_name'])) {
if (!\is_string($data['serialized_name']) || '' === $data['serialized_name']) {
throw new MappingException(sprintf('The "serialized_name" value must be a non-empty string in "%s" for the attribute "%s" of the class "%s".', $this->file, $attribute, $classMetadata->getName()));
}

$attributeMetadata->setSerializedName($data['serialized_name']);
}

if (isset($data['serialized_path'])) {
try {
$attributeMetadata->setSerializedPath(new PropertyPath((string) $data['serialized_path']));
} catch (InvalidPropertyPathException) {
throw new MappingException(sprintf('The "serialized_path" value must be a valid property path in "%s" for the attribute "%s" of the class "%s".', $this->file, $attribute, $classMetadata->getName()));
}
}

if (isset($data['ignore'])) {
if (!\is_bool($data['ignore'])) {
throw new MappingException(sprintf('The "ignore" value must be a boolean in "%s" for the attribute "%s" of the class "%s".', $this->file, $attribute, $classMetadata->getName()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,13 @@
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name="serialized-path">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:minLength value="1" />
</xsd:restriction>
</xsd:simpleType>
</xsd:attribute>
<xsd:attribute name="ignore" type="xsd:boolean" />
</xsd:complexType>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Component\Serializer\NameConverter;

use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;

Expand Down Expand Up @@ -76,6 +77,10 @@ private function getCacheValueForNormalization(string $propertyName, string $cla
return null;
}

if (null !== $attributesMetadata[$propertyName]->getSerializedName() && null !== $attributesMetadata[$propertyName]->getSerializedPath()) {
throw new LogicException(sprintf('Found SerializedName and SerializedPath annotations on property "%s" of class "%s".', $propertyName, $class));
}

return $attributesMetadata[$propertyName]->getSerializedName() ?? null;
}

Expand Down Expand Up @@ -113,6 +118,10 @@ private function getCacheValueForAttributesMetadata(string $class, array $contex
continue;
}

if (null !== $metadata->getSerializedName() && null !== $metadata->getSerializedPath()) {
throw new LogicException(sprintf('Found SerializedName and SerializedPath annotations on property "%s" of class "%s".', $name, $class));
}

$groups = $metadata->getGroups();
if (!$groups && ($context[AbstractNormalizer::GROUPS] ?? [])) {
continue;
Expand Down
Loading