From 5b745cdc0896cb674cfb7c005d3156bb93d98efb Mon Sep 17 00:00:00 2001 From: Frank de Jonge Date: Sun, 5 Jun 2022 12:26:06 +0200 Subject: [PATCH] Only reverse order of serializers for promoted properties. --- README.md | 4 ++-- src/DefinitionProvider.php | 10 ++++++++-- src/PropertySerializationDefinition.php | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 877397b..315a593 100644 --- a/README.md +++ b/README.md @@ -612,10 +612,10 @@ It's important to know that serialization and hydration hooks are triggered befo happens. If you wish to operate on serialized or hydrated data, you can hydrate/serialize the inner data/objects. -### Caster and serializer order +### ⚠️ Caster and serializer order In order to make hydration and serialization symmetrical (allowing back and forth conversion), the order -of serializers called is reversed. +of serializers called is reversed for _promoted_ properties. ## Maximizing performance diff --git a/src/DefinitionProvider.php b/src/DefinitionProvider.php index dbbda37..3a44d67 100644 --- a/src/DefinitionProvider.php +++ b/src/DefinitionProvider.php @@ -12,6 +12,7 @@ use ReflectionProperty; use ReflectionUnionType; use function array_key_exists; +use function array_reverse; use function count; use function is_a; @@ -161,10 +162,15 @@ public function provideSerializationDefinition(string $className): ClassSerializ $key = $this->keyFormatter->propertyNameToKey($property->getName()); $propertyType = $property->getType(); $attributes = $property->getAttributes(); + $serializers = $this->resolveSerializers($propertyType, $attributes); + + if ($property->isPromoted()) { + $serializers = array_reverse($serializers); + } + $properties[] = new PropertySerializationDefinition( PropertySerializationDefinition::TYPE_PROPERTY, - $property->getName(), - $this->resolveSerializers($propertyType, $attributes), + $property->getName(), $serializers, PropertyType::fromReflectionType($propertyType), $propertyType->allowsNull(), $this->resolveKeys($key, $attributes), diff --git a/src/PropertySerializationDefinition.php b/src/PropertySerializationDefinition.php index 989cb07..ac35d2b 100644 --- a/src/PropertySerializationDefinition.php +++ b/src/PropertySerializationDefinition.php @@ -20,7 +20,7 @@ public function __construct( public bool $nullable, public array $keys = [], ) { - $this->serializers = array_reverse(array_filter($this->serializers)); + $this->serializers = array_filter($this->serializers); } public function formattedAccessor(): string