From a5d840e0aabb5595c42e0371b7bf6819afa59d95 Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 19:57:40 +0100 Subject: [PATCH 1/9] Keep keys without a normalizer in array shapes ArrayShapeNormalizer only returned the keys it had an inner normalizer for, so every other key of the shape was silently dropped on extract and hydrate. Keys holding null were dropped too because of isset(). The normalizer now works on the given array and only converts the keys it has a normalizer for, null included, and keeps everything else as it is, like ArrayNormalizer and plain arrays do. --- README.md | 6 ++ src/Normalizer/ArrayShapeNormalizer.php | 21 +++--- .../InferNormalizerWithArrayShapeDto.php | 16 +++++ tests/Unit/MetadataHydratorTest.php | 25 +++++++ .../Normalizer/ArrayShapeNormalizerTest.php | 66 +++++++++++++++++++ tests/Unit/StackHydratorTest.php | 25 +++++++ 6 files changed, 147 insertions(+), 12 deletions(-) create mode 100644 tests/Unit/Fixture/InferNormalizerWithArrayShapeDto.php diff --git a/README.md b/README.md index d5081c3c..85650d4d 100644 --- a/README.md +++ b/README.md @@ -211,6 +211,12 @@ final class DTO } ``` +> [!NOTE] +> Only the keys with a normalizer are converted. All other keys, including keys +> that are not part of the shape, are kept as they are, so they must already hold +> values that your storage can handle. A `null` value is passed to the normalizer +> of its key, like for any other property. + #### DateTimeImmutable With the `DateTimeImmutable` Normalizer, as the name suggests, diff --git a/src/Normalizer/ArrayShapeNormalizer.php b/src/Normalizer/ArrayShapeNormalizer.php index ef517b6a..b07b53d5 100644 --- a/src/Normalizer/ArrayShapeNormalizer.php +++ b/src/Normalizer/ArrayShapeNormalizer.php @@ -10,6 +10,7 @@ use Symfony\Component\TypeInfo\Type\ArrayShapeType; use Symfony\Component\TypeInfo\Type\NullableType; +use function array_key_exists; use function is_array; #[Attribute(Attribute::TARGET_PROPERTY)] @@ -36,21 +37,19 @@ public function normalize(mixed $value, array $context = []): array|null throw InvalidArgument::withWrongType('array|null', $value); } - $result = []; - foreach ($this->normalizerMap as $field => $normalizer) { - if (!isset($value[$field])) { + if (!array_key_exists($field, $value)) { continue; } if ($normalizer instanceof NormalizerWithContext) { - $result[$field] = $normalizer->normalize($value[$field], $context); + $value[$field] = $normalizer->normalize($value[$field], $context); } else { - $result[$field] = $normalizer->normalize($value[$field]); + $value[$field] = $normalizer->normalize($value[$field]); } } - return $result; + return $value; } /** @@ -68,21 +67,19 @@ public function denormalize(mixed $value, array $context = []): array|null throw InvalidArgument::withWrongType('array|null', $value); } - $result = []; - foreach ($this->normalizerMap as $field => $normalizer) { - if (!isset($value[$field])) { + if (!array_key_exists($field, $value)) { continue; } if ($normalizer instanceof NormalizerWithContext) { - $result[$field] = $normalizer->denormalize($value[$field], $context); + $value[$field] = $normalizer->denormalize($value[$field], $context); } else { - $result[$field] = $normalizer->denormalize($value[$field]); + $value[$field] = $normalizer->denormalize($value[$field]); } } - return $result; + return $value; } public function setHydrator(Hydrator $hydrator): void diff --git a/tests/Unit/Fixture/InferNormalizerWithArrayShapeDto.php b/tests/Unit/Fixture/InferNormalizerWithArrayShapeDto.php new file mode 100644 index 00000000..d96cc256 --- /dev/null +++ b/tests/Unit/Fixture/InferNormalizerWithArrayShapeDto.php @@ -0,0 +1,16 @@ +, status: Status|null, createdAt: DateTimeImmutable} $profile */ + public function __construct( + public array $profile, + ) { + } +} diff --git a/tests/Unit/MetadataHydratorTest.php b/tests/Unit/MetadataHydratorTest.php index 88b66a77..c3ba1051 100644 --- a/tests/Unit/MetadataHydratorTest.php +++ b/tests/Unit/MetadataHydratorTest.php @@ -28,6 +28,7 @@ use Patchlevel\Hydrator\Tests\Unit\Fixture\Email; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerBrokenDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerDto; +use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithArrayShapeDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithIterablesDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithNullableDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\LazyProfileCreated; @@ -572,6 +573,30 @@ public function testHydrateWithInferNormalizerWitIterables(): void self::assertEquals($expected, $event); } + public function testRoundTripWithArrayShape(): void + { + $object = new InferNormalizerWithArrayShapeDto([ + 'height' => 180, + 'nickname' => null, + 'skills' => [new Skill('php'), new Skill('go')], + 'status' => null, + 'createdAt' => new DateTimeImmutable('2015-02-13 22:34:32+01:00'), + ]); + + $data = [ + 'profile' => [ + 'height' => 180, + 'nickname' => null, + 'skills' => [['name' => 'php'], ['name' => 'go']], + 'status' => null, + 'createdAt' => '2015-02-13T22:34:32+01:00', + ], + ]; + + self::assertSame($data, $this->hydrator->extract($object)); + self::assertEquals($object, $this->hydrator->hydrate(InferNormalizerWithArrayShapeDto::class, $data)); + } + public function testHydrateWithInferNormalizerFailed(): void { $this->expectException(TypeMismatch::class); diff --git a/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php b/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php index a85a6e44..98c6f424 100644 --- a/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php +++ b/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php @@ -90,6 +90,72 @@ public function denormalize(mixed $value): int $this->assertEquals(['foo' => 1], $normalizer->denormalize(['foo' => '1'])); } + public function testNormalizeKeepsKeysWithoutNormalizer(): void + { + $innerNormalizer = $this->createMock(Normalizer::class); + $innerNormalizer->expects($this->once())->method('normalize')->with(1)->willReturn('1'); + + $normalizer = new ArrayShapeNormalizer(['foo' => $innerNormalizer]); + + $this->assertSame( + ['height' => 180, 'foo' => '1', 'note' => null, 'unknown' => ['x']], + $normalizer->normalize(['height' => 180, 'foo' => 1, 'note' => null, 'unknown' => ['x']]), + ); + } + + public function testDenormalizeKeepsKeysWithoutNormalizer(): void + { + $innerNormalizer = $this->createMock(Normalizer::class); + $innerNormalizer->expects($this->once())->method('denormalize')->with('1')->willReturn(1); + + $normalizer = new ArrayShapeNormalizer(['foo' => $innerNormalizer]); + + $this->assertSame( + ['height' => 180, 'foo' => 1, 'note' => null, 'unknown' => ['x']], + $normalizer->denormalize(['height' => 180, 'foo' => '1', 'note' => null, 'unknown' => ['x']]), + ); + } + + public function testNormalizePassesNullToInnerNormalizer(): void + { + $innerNormalizer = $this->createMock(Normalizer::class); + $innerNormalizer->expects($this->once())->method('normalize')->with(null)->willReturn(null); + + $normalizer = new ArrayShapeNormalizer(['foo' => $innerNormalizer]); + + $this->assertSame(['foo' => null], $normalizer->normalize(['foo' => null])); + } + + public function testDenormalizePassesNullToInnerNormalizer(): void + { + $innerNormalizer = $this->createMock(Normalizer::class); + $innerNormalizer->expects($this->once())->method('denormalize')->with(null)->willReturn(null); + + $normalizer = new ArrayShapeNormalizer(['foo' => $innerNormalizer]); + + $this->assertSame(['foo' => null], $normalizer->denormalize(['foo' => null])); + } + + public function testNormalizeSkipsMissingKeys(): void + { + $innerNormalizer = $this->createMock(Normalizer::class); + $innerNormalizer->expects($this->never())->method('normalize'); + + $normalizer = new ArrayShapeNormalizer(['foo' => $innerNormalizer]); + + $this->assertSame(['bar' => 1], $normalizer->normalize(['bar' => 1])); + } + + public function testDenormalizeSkipsMissingKeys(): void + { + $innerNormalizer = $this->createMock(Normalizer::class); + $innerNormalizer->expects($this->never())->method('denormalize'); + + $normalizer = new ArrayShapeNormalizer(['foo' => $innerNormalizer]); + + $this->assertSame(['bar' => 1], $normalizer->denormalize(['bar' => 1])); + } + public function testNormalizePassesContextToInnerNormalizer(): void { $context = ['key' => 'value']; diff --git a/tests/Unit/StackHydratorTest.php b/tests/Unit/StackHydratorTest.php index 4ec1fcb0..db3a25f6 100644 --- a/tests/Unit/StackHydratorTest.php +++ b/tests/Unit/StackHydratorTest.php @@ -27,6 +27,7 @@ use Patchlevel\Hydrator\Tests\Unit\Fixture\DefaultDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\Email; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerDto; +use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithArrayShapeDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithIterablesDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithNullableDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\LazyProfileCreated; @@ -500,6 +501,30 @@ public function testHydrateWithInferNormalizerWitIterables(): void self::assertEquals($expected, $event); } + public function testRoundTripWithArrayShape(): void + { + $object = new InferNormalizerWithArrayShapeDto([ + 'height' => 180, + 'nickname' => null, + 'skills' => [new Skill('php'), new Skill('go')], + 'status' => null, + 'createdAt' => new DateTimeImmutable('2015-02-13 22:34:32+01:00'), + ]); + + $data = [ + 'profile' => [ + 'height' => 180, + 'nickname' => null, + 'skills' => [['name' => 'php'], ['name' => 'go']], + 'status' => null, + 'createdAt' => '2015-02-13T22:34:32+01:00', + ], + ]; + + self::assertSame($data, $this->hydrator->extract($object)); + self::assertEquals($object, $this->hydrator->hydrate(InferNormalizerWithArrayShapeDto::class, $data)); + } + #[RequiresPhp('>=8.4')] public function testLazyHydrate(): void { From 026d8045bfea658d8f5151ef094aae1e04cbb621 Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 20:00:16 +0100 Subject: [PATCH 2/9] Infer normalizers for nullable collection items The collection branch unwrapped the nullable item type from the collection itself instead of from the item type, so collections like list got no normalizer at all and their items were passed through as raw objects. --- phpstan-baseline.neon | 8 +++--- src/Metadata/AttributeMetadataFactory.php | 2 +- .../InferNormalizerWithNullableItemsDto.php | 24 +++++++++++++++++ .../Metadata/AttributeMetadataFactoryTest.php | 27 +++++++++++++++++++ tests/Unit/MetadataHydratorTest.php | 24 +++++++++++++++++ tests/Unit/StackHydratorTest.php | 24 +++++++++++++++++ 6 files changed, 104 insertions(+), 5 deletions(-) create mode 100644 tests/Unit/Fixture/InferNormalizerWithNullableItemsDto.php diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index c012db30..0dcfe9f1 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -223,13 +223,13 @@ parameters: path: tests/Unit/Fixture/DtoWithHooks.php - - message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:477\:\:postHydrate\(\) is unused\.$#' + message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:481\:\:postHydrate\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php - - message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:477\:\:preExtract\(\) is unused\.$#' + message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:481\:\:preExtract\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php @@ -241,13 +241,13 @@ parameters: path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php - - message: '#^Static method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:505\:\:postHydrate\(\) is unused\.$#' + message: '#^Static method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:509\:\:postHydrate\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php - - message: '#^Static method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:505\:\:preExtract\(\) is unused\.$#' + message: '#^Static method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:509\:\:preExtract\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php diff --git a/src/Metadata/AttributeMetadataFactory.php b/src/Metadata/AttributeMetadataFactory.php index 7a13d505..3a892111 100644 --- a/src/Metadata/AttributeMetadataFactory.php +++ b/src/Metadata/AttributeMetadataFactory.php @@ -453,7 +453,7 @@ private function inferNormalizerByType(Type $type): Normalizer|null $valueType = $type->getCollectionValueType(); if ($valueType instanceof NullableType) { - $valueType = $type->getWrappedType(); + $valueType = $valueType->getWrappedType(); } $normalizer = null; diff --git a/tests/Unit/Fixture/InferNormalizerWithNullableItemsDto.php b/tests/Unit/Fixture/InferNormalizerWithNullableItemsDto.php new file mode 100644 index 00000000..894e6c97 --- /dev/null +++ b/tests/Unit/Fixture/InferNormalizerWithNullableItemsDto.php @@ -0,0 +1,24 @@ + $skills + * @param array $statuses + * @param list $dates + * @param array>|null $nested + */ + public function __construct( + public array $skills = [], + public array $statuses = [], + public array $dates = [], + public array|null $nested = null, + ) { + } +} diff --git a/tests/Unit/Metadata/AttributeMetadataFactoryTest.php b/tests/Unit/Metadata/AttributeMetadataFactoryTest.php index 149a6b60..fd153301 100644 --- a/tests/Unit/Metadata/AttributeMetadataFactoryTest.php +++ b/tests/Unit/Metadata/AttributeMetadataFactoryTest.php @@ -17,6 +17,8 @@ use Patchlevel\Hydrator\Metadata\MultipleDataSubjectId; use Patchlevel\Hydrator\Metadata\PropertyMetadataNotFound; use Patchlevel\Hydrator\Metadata\SubjectIdAndPersonalDataConflict; +use Patchlevel\Hydrator\Normalizer\ArrayNormalizer; +use Patchlevel\Hydrator\Normalizer\DateTimeImmutableNormalizer; use Patchlevel\Hydrator\Normalizer\EnumNormalizer; use Patchlevel\Hydrator\Normalizer\ObjectNormalizer; use Patchlevel\Hydrator\Tests\Unit\Fixture\BrokenParentDto; @@ -27,11 +29,13 @@ use Patchlevel\Hydrator\Tests\Unit\Fixture\IdNormalizer; use Patchlevel\Hydrator\Tests\Unit\Fixture\IgnoreDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\IgnoreParentDto; +use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithNullableItemsDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\MissingSubjectIdDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\ParentDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\ParentWithPersonalDataDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileCreatedWithGeneric; use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileId; +use Patchlevel\Hydrator\Tests\Unit\Fixture\Skill; use Patchlevel\Hydrator\Tests\Unit\Fixture\Status; use Patchlevel\Hydrator\Tests\Unit\Fixture\Wrapper; use PHPUnit\Framework\TestCase; @@ -543,4 +547,27 @@ class { self::assertTrue($metadata->lazy()); } + + public function testInferNormalizerForNullableCollectionItems(): void + { + $metadataFactory = new AttributeMetadataFactory(); + $metadata = $metadataFactory->metadata(InferNormalizerWithNullableItemsDto::class); + + self::assertEquals( + new ArrayNormalizer(new ObjectNormalizer(Skill::class)), + $metadata->propertyForField('skills')->normalizer, + ); + self::assertEquals( + new ArrayNormalizer(new EnumNormalizer(Status::class)), + $metadata->propertyForField('statuses')->normalizer, + ); + self::assertEquals( + new ArrayNormalizer(new DateTimeImmutableNormalizer()), + $metadata->propertyForField('dates')->normalizer, + ); + self::assertEquals( + new ArrayNormalizer(new ArrayNormalizer(new EnumNormalizer(Status::class))), + $metadata->propertyForField('nested')->normalizer, + ); + } } diff --git a/tests/Unit/MetadataHydratorTest.php b/tests/Unit/MetadataHydratorTest.php index c3ba1051..faca3f6b 100644 --- a/tests/Unit/MetadataHydratorTest.php +++ b/tests/Unit/MetadataHydratorTest.php @@ -31,6 +31,7 @@ use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithArrayShapeDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithIterablesDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithNullableDto; +use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithNullableItemsDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\LazyProfileCreated; use Patchlevel\Hydrator\Tests\Unit\Fixture\NormalizerInBaseClassDefinedDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\ParentDto; @@ -573,6 +574,29 @@ public function testHydrateWithInferNormalizerWitIterables(): void self::assertEquals($expected, $event); } + public function testRoundTripWithInferNormalizerForNullableCollectionItems(): void + { + $object = new InferNormalizerWithNullableItemsDto( + [new Skill('php'), null], + ['foo' => Status::Draft, 'bar' => null], + [new DateTimeImmutable('2015-02-13 22:34:32+01:00'), null], + ['foo' => [Status::Closed, null]], + ); + + $data = [ + 'skills' => [['name' => 'php'], null], + 'statuses' => ['foo' => 'draft', 'bar' => null], + 'dates' => ['2015-02-13T22:34:32+01:00', null], + 'nested' => ['foo' => ['closed', null]], + ]; + + self::assertSame($data, $this->hydrator->extract($object)); + self::assertEquals( + $object, + $this->hydrator->hydrate(InferNormalizerWithNullableItemsDto::class, $data), + ); + } + public function testRoundTripWithArrayShape(): void { $object = new InferNormalizerWithArrayShapeDto([ diff --git a/tests/Unit/StackHydratorTest.php b/tests/Unit/StackHydratorTest.php index db3a25f6..73e48dda 100644 --- a/tests/Unit/StackHydratorTest.php +++ b/tests/Unit/StackHydratorTest.php @@ -30,6 +30,7 @@ use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithArrayShapeDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithIterablesDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithNullableDto; +use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithNullableItemsDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\LazyProfileCreated; use Patchlevel\Hydrator\Tests\Unit\Fixture\NormalizerInBaseClassDefinedDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\ParentDto; @@ -501,6 +502,29 @@ public function testHydrateWithInferNormalizerWitIterables(): void self::assertEquals($expected, $event); } + public function testRoundTripWithInferNormalizerForNullableCollectionItems(): void + { + $object = new InferNormalizerWithNullableItemsDto( + [new Skill('php'), null], + ['foo' => Status::Draft, 'bar' => null], + [new DateTimeImmutable('2015-02-13 22:34:32+01:00'), null], + ['foo' => [Status::Closed, null]], + ); + + $data = [ + 'skills' => [['name' => 'php'], null], + 'statuses' => ['foo' => 'draft', 'bar' => null], + 'dates' => ['2015-02-13T22:34:32+01:00', null], + 'nested' => ['foo' => ['closed', null]], + ]; + + self::assertSame($data, $this->hydrator->extract($object)); + self::assertEquals( + $object, + $this->hydrator->hydrate(InferNormalizerWithNullableItemsDto::class, $data), + ); + } + public function testRoundTripWithArrayShape(): void { $object = new InferNormalizerWithArrayShapeDto([ From dc351f908be4702f7e4df2829342bd0377c252cc Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 20:01:02 +0100 Subject: [PATCH 3/9] Skip array shape fields without type info in handleType An explicit ArrayShapeNormalizer map can contain keys that the property's docblock shape doesn't know. handleType read those keys anyway and raised undefined key warnings. Such fields are now left alone, like the whole map is when the property type isn't an array shape. --- src/Normalizer/ArrayShapeNormalizer.php | 2 +- .../ExplicitArrayShapeNormalizerDto.php | 22 +++++++++++++++ tests/Unit/MetadataHydratorTest.php | 22 +++++++++++++++ .../Normalizer/ArrayShapeNormalizerTest.php | 27 +++++++++++++++++++ tests/Unit/StackHydratorTest.php | 22 +++++++++++++++ 5 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 tests/Unit/Fixture/ExplicitArrayShapeNormalizerDto.php diff --git a/src/Normalizer/ArrayShapeNormalizer.php b/src/Normalizer/ArrayShapeNormalizer.php index b07b53d5..967ee490 100644 --- a/src/Normalizer/ArrayShapeNormalizer.php +++ b/src/Normalizer/ArrayShapeNormalizer.php @@ -110,7 +110,7 @@ public function handleType(Type|null $type): void $shape = $type->getShape(); foreach ($this->normalizerMap as $field => $normalizer) { - if (!$normalizer instanceof TypeAwareNormalizer) { + if (!$normalizer instanceof TypeAwareNormalizer || !array_key_exists($field, $shape)) { continue; } diff --git a/tests/Unit/Fixture/ExplicitArrayShapeNormalizerDto.php b/tests/Unit/Fixture/ExplicitArrayShapeNormalizerDto.php new file mode 100644 index 00000000..9b1bb91a --- /dev/null +++ b/tests/Unit/Fixture/ExplicitArrayShapeNormalizerDto.php @@ -0,0 +1,22 @@ + new EnumNormalizer(), + 'skill' => new ObjectNormalizer(Skill::class), + ])] + public array|null $shape = null, + ) { + } +} diff --git a/tests/Unit/MetadataHydratorTest.php b/tests/Unit/MetadataHydratorTest.php index faca3f6b..5b32b604 100644 --- a/tests/Unit/MetadataHydratorTest.php +++ b/tests/Unit/MetadataHydratorTest.php @@ -26,6 +26,7 @@ use Patchlevel\Hydrator\Tests\Unit\Fixture\DefaultDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\DtoWithHooks; use Patchlevel\Hydrator\Tests\Unit\Fixture\Email; +use Patchlevel\Hydrator\Tests\Unit\Fixture\ExplicitArrayShapeNormalizerDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerBrokenDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithArrayShapeDto; @@ -621,6 +622,27 @@ public function testRoundTripWithArrayShape(): void self::assertEquals($object, $this->hydrator->hydrate(InferNormalizerWithArrayShapeDto::class, $data)); } + public function testRoundTripWithExplicitArrayShapeNormalizerAndFieldMissingInDocblock(): void + { + $object = new ExplicitArrayShapeNormalizerDto([ + 'status' => Status::Draft, + 'skill' => new Skill('php'), + ]); + + $data = [ + 'shape' => [ + 'status' => 'draft', + 'skill' => ['name' => 'php'], + ], + ]; + + self::assertSame($data, $this->hydrator->extract($object)); + self::assertEquals( + $object, + $this->hydrator->hydrate(ExplicitArrayShapeNormalizerDto::class, $data), + ); + } + public function testHydrateWithInferNormalizerFailed(): void { $this->expectException(TypeMismatch::class); diff --git a/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php b/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php index 98c6f424..17dd5005 100644 --- a/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php +++ b/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php @@ -7,11 +7,15 @@ use Attribute; use Patchlevel\Hydrator\Hydrator; use Patchlevel\Hydrator\Normalizer\ArrayShapeNormalizer; +use Patchlevel\Hydrator\Normalizer\EnumNormalizer; use Patchlevel\Hydrator\Normalizer\HydratorAwareNormalizer; use Patchlevel\Hydrator\Normalizer\InvalidArgument; use Patchlevel\Hydrator\Normalizer\Normalizer; use Patchlevel\Hydrator\Normalizer\NormalizerWithContext; +use Patchlevel\Hydrator\Normalizer\TypeAwareNormalizer; +use Patchlevel\Hydrator\Tests\Unit\Fixture\Status; use PHPUnit\Framework\TestCase; +use Symfony\Component\TypeInfo\Type; #[Attribute(Attribute::TARGET_PROPERTY)] final class ArrayShapeNormalizerTest extends TestCase @@ -228,6 +232,29 @@ public function testPassHydrator(): void $normalizer->setHydrator($hydrator); } + public function testHandleTypePassesFieldTypes(): void + { + $innerNormalizer = new EnumNormalizer(); + + $normalizer = new ArrayShapeNormalizer(['status' => $innerNormalizer]); + $normalizer->handleType(Type::nullable(Type::arrayShape(['status' => Type::enum(Status::class)]))); + + self::assertSame(Status::class, $innerNormalizer->className()); + } + + public function testHandleTypeSkipsFieldsMissingInShape(): void + { + $statusNormalizer = new EnumNormalizer(); + + $missingNormalizer = $this->createMockForIntersectionOfInterfaces([Normalizer::class, TypeAwareNormalizer::class]); + $missingNormalizer->expects($this->never())->method('handleType'); + + $normalizer = new ArrayShapeNormalizer(['status' => $statusNormalizer, 'missing' => $missingNormalizer]); + $normalizer->handleType(Type::arrayShape(['status' => Type::enum(Status::class)])); + + self::assertSame(Status::class, $statusNormalizer->className()); + } + public function testInnerNormalizers(): void { $innerNormalizer = $this->createMock(Normalizer::class); diff --git a/tests/Unit/StackHydratorTest.php b/tests/Unit/StackHydratorTest.php index 73e48dda..34e17cfb 100644 --- a/tests/Unit/StackHydratorTest.php +++ b/tests/Unit/StackHydratorTest.php @@ -26,6 +26,7 @@ use Patchlevel\Hydrator\Tests\Unit\Fixture\Circle3Dto; use Patchlevel\Hydrator\Tests\Unit\Fixture\DefaultDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\Email; +use Patchlevel\Hydrator\Tests\Unit\Fixture\ExplicitArrayShapeNormalizerDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithArrayShapeDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithIterablesDto; @@ -549,6 +550,27 @@ public function testRoundTripWithArrayShape(): void self::assertEquals($object, $this->hydrator->hydrate(InferNormalizerWithArrayShapeDto::class, $data)); } + public function testRoundTripWithExplicitArrayShapeNormalizerAndFieldMissingInDocblock(): void + { + $object = new ExplicitArrayShapeNormalizerDto([ + 'status' => Status::Draft, + 'skill' => new Skill('php'), + ]); + + $data = [ + 'shape' => [ + 'status' => 'draft', + 'skill' => ['name' => 'php'], + ], + ]; + + self::assertSame($data, $this->hydrator->extract($object)); + self::assertEquals( + $object, + $this->hydrator->hydrate(ExplicitArrayShapeNormalizerDto::class, $data), + ); + } + #[RequiresPhp('>=8.4')] public function testLazyHydrate(): void { From ef67f36e53828065e18c97ed2484d80b77588207 Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 20:02:01 +0100 Subject: [PATCH 4/9] Let inferNormalizerByType unwrap collection and shape items itself The collection and array shape branches unwrapped nullable item types and looked for a class normalizer before recursing, although inferNormalizerByType does both on its own. Dropping the duplicate removes the place where the nullable item bug came from. The shape branch is now also covered in the metadata factory test. --- phpstan-baseline.neon | 10 +++--- src/Metadata/AttributeMetadataFactory.php | 32 ++----------------- ...ferNormalizerWithNullableShapeItemsDto.php | 14 ++++++++ .../Metadata/AttributeMetadataFactoryTest.php | 16 ++++++++++ 4 files changed, 37 insertions(+), 35 deletions(-) create mode 100644 tests/Unit/Fixture/InferNormalizerWithNullableShapeItemsDto.php diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 0dcfe9f1..a214789a 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -111,7 +111,7 @@ parameters: - message: '#^Parameter \#1 \$class of method Patchlevel\\Hydrator\\Metadata\\AttributeMetadataFactory\:\:findNormalizerOnClass\(\) expects class\-string, string given\.$#' identifier: argument.type - count: 3 + count: 1 path: src/Metadata/AttributeMetadataFactory.php - @@ -223,13 +223,13 @@ parameters: path: tests/Unit/Fixture/DtoWithHooks.php - - message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:481\:\:postHydrate\(\) is unused\.$#' + message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:483\:\:postHydrate\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php - - message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:481\:\:preExtract\(\) is unused\.$#' + message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:483\:\:preExtract\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php @@ -241,13 +241,13 @@ parameters: path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php - - message: '#^Static method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:509\:\:postHydrate\(\) is unused\.$#' + message: '#^Static method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:511\:\:postHydrate\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php - - message: '#^Static method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:509\:\:preExtract\(\) is unused\.$#' + message: '#^Static method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:511\:\:preExtract\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php diff --git a/src/Metadata/AttributeMetadataFactory.php b/src/Metadata/AttributeMetadataFactory.php index 3a892111..c2fed37d 100644 --- a/src/Metadata/AttributeMetadataFactory.php +++ b/src/Metadata/AttributeMetadataFactory.php @@ -419,21 +419,7 @@ private function inferNormalizerByType(Type $type): Normalizer|null $normalizers = []; foreach ($shape as $field => $fieldInfo) { - $valueType = $fieldInfo['type']; - - if ($valueType instanceof NullableType) { - $valueType = $valueType->getWrappedType(); - } - - $normalizer = null; - - if ($valueType instanceof ObjectType) { - $normalizer = $this->findNormalizerOnClass($valueType->getClassName()); - } - - if ($normalizer === null) { - $normalizer = $this->inferNormalizerByType($valueType); - } + $normalizer = $this->inferNormalizerByType($fieldInfo['type']); if ($normalizer === null) { continue; @@ -450,21 +436,7 @@ private function inferNormalizerByType(Type $type): Normalizer|null } if ($type instanceof CollectionType) { - $valueType = $type->getCollectionValueType(); - - if ($valueType instanceof NullableType) { - $valueType = $valueType->getWrappedType(); - } - - $normalizer = null; - - if ($valueType instanceof ObjectType) { - $normalizer = $this->findNormalizerOnClass($valueType->getClassName()); - } - - if ($normalizer === null) { - $normalizer = $this->inferNormalizerByType($valueType); - } + $normalizer = $this->inferNormalizerByType($type->getCollectionValueType()); if ($normalizer) { return new ArrayNormalizer($normalizer); diff --git a/tests/Unit/Fixture/InferNormalizerWithNullableShapeItemsDto.php b/tests/Unit/Fixture/InferNormalizerWithNullableShapeItemsDto.php new file mode 100644 index 00000000..c49fb476 --- /dev/null +++ b/tests/Unit/Fixture/InferNormalizerWithNullableShapeItemsDto.php @@ -0,0 +1,14 @@ +propertyForField('nested')->normalizer, ); } + + public function testInferNormalizerForNullableArrayShapeFields(): void + { + $metadataFactory = new AttributeMetadataFactory(); + $metadata = $metadataFactory->metadata(InferNormalizerWithNullableShapeItemsDto::class); + + self::assertEquals( + new ArrayShapeNormalizer([ + 'skill' => new ObjectNormalizer(Skill::class), + 'status' => new EnumNormalizer(Status::class), + ]), + $metadata->propertyForField('shape')->normalizer, + ); + } } From e3e8a101c0d0fc74ff02c42c3cee17df4f86f943 Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 20:03:31 +0100 Subject: [PATCH 5/9] Let the child class win when merging inherited metadata The parameter names of mergeMetadata() were swapped relative to the call site, so the lazy flag of the parent took precedence over the child's. A class with #[Lazy(false)] extending a #[Lazy] class was still hydrated lazily. Everything else keeps its current order: properties, callbacks and the data subject id of the child still come first. --- phpstan-baseline.neon | 8 +++--- src/Metadata/AttributeMetadataFactory.php | 26 +++++++++---------- tests/Unit/Fixture/BaseLazyDto.php | 12 +++++++++ .../Metadata/AttributeMetadataFactoryTest.php | 24 +++++++++++++++++ 4 files changed, 53 insertions(+), 17 deletions(-) create mode 100644 tests/Unit/Fixture/BaseLazyDto.php diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index a214789a..c417d53a 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -223,13 +223,13 @@ parameters: path: tests/Unit/Fixture/DtoWithHooks.php - - message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:483\:\:postHydrate\(\) is unused\.$#' + message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:484\:\:postHydrate\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php - - message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:483\:\:preExtract\(\) is unused\.$#' + message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:484\:\:preExtract\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php @@ -241,13 +241,13 @@ parameters: path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php - - message: '#^Static method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:511\:\:postHydrate\(\) is unused\.$#' + message: '#^Static method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:512\:\:postHydrate\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php - - message: '#^Static method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:511\:\:preExtract\(\) is unused\.$#' + message: '#^Static method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:512\:\:preExtract\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php diff --git a/src/Metadata/AttributeMetadataFactory.php b/src/Metadata/AttributeMetadataFactory.php index c2fed37d..6c70208d 100644 --- a/src/Metadata/AttributeMetadataFactory.php +++ b/src/Metadata/AttributeMetadataFactory.php @@ -250,48 +250,48 @@ private function hasIgnore(ReflectionProperty $reflectionProperty): bool } /** - * @param ClassMetadata $parent + * @param ClassMetadata $child * * @return ClassMetadata * * @template T of object */ - private function mergeMetadata(ClassMetadata $parent, ClassMetadata $child): ClassMetadata + private function mergeMetadata(ClassMetadata $child, ClassMetadata $parent): ClassMetadata { $properties = []; - foreach ($parent->properties() as $property) { + foreach ($child->properties() as $property) { $properties[$property->fieldName()] = $property; } - foreach ($child->properties() as $property) { + foreach ($parent->properties() as $property) { if (array_key_exists($property->fieldName(), $properties)) { throw DuplicatedFieldNameInMetadata::byInheritance( $property->fieldName(), - $parent->className(), $child->className(), + $parent->className(), ); } $properties[$property->fieldName()] = $property; } - $parentDataSubjectIdField = $parent->dataSubjectIdField(); $childDataSubjectIdField = $child->dataSubjectIdField(); + $parentDataSubjectIdField = $parent->dataSubjectIdField(); - if ($parentDataSubjectIdField !== null && $childDataSubjectIdField !== null) { - $parentProperty = $parent->propertyForField($parentDataSubjectIdField); + if ($childDataSubjectIdField !== null && $parentDataSubjectIdField !== null) { $childProperty = $child->propertyForField($childDataSubjectIdField); + $parentProperty = $parent->propertyForField($parentDataSubjectIdField); - throw new MultipleDataSubjectId($parentProperty->propertyName(), $childProperty->propertyName()); + throw new MultipleDataSubjectId($childProperty->propertyName(), $parentProperty->propertyName()); } return new ClassMetadata( - $parent->reflection(), + $child->reflection(), array_values($properties), - $parentDataSubjectIdField ?? $childDataSubjectIdField, - array_merge($parent->postHydrateCallbacks(), $child->postHydrateCallbacks()), - array_merge($parent->preExtractCallbacks(), $child->preExtractCallbacks()), + $childDataSubjectIdField ?? $parentDataSubjectIdField, + array_merge($child->postHydrateCallbacks(), $parent->postHydrateCallbacks()), + array_merge($child->preExtractCallbacks(), $parent->preExtractCallbacks()), $child->lazy() ?? $parent->lazy(), ); } diff --git a/tests/Unit/Fixture/BaseLazyDto.php b/tests/Unit/Fixture/BaseLazyDto.php new file mode 100644 index 00000000..9cc4a4e6 --- /dev/null +++ b/tests/Unit/Fixture/BaseLazyDto.php @@ -0,0 +1,12 @@ +lazy()); } + public function testLazyIsInheritedFromParent(): void + { + $object = new class extends BaseLazyDto { + }; + + $metadataFactory = new AttributeMetadataFactory(); + $metadata = $metadataFactory->metadata($object::class); + + self::assertTrue($metadata->lazy); + } + + public function testLazyOfChildWinsOverParent(): void + { + $object = new #[Lazy(false)] + class extends BaseLazyDto { + }; + + $metadataFactory = new AttributeMetadataFactory(); + $metadata = $metadataFactory->metadata($object::class); + + self::assertFalse($metadata->lazy); + } + public function testInferNormalizerForNullableCollectionItems(): void { $metadataFactory = new AttributeMetadataFactory(); From 90ac2f4c8306e1bb9673fac02c9446987d7210f8 Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 20:20:50 +0100 Subject: [PATCH 6/9] Run inherited lifecycle callbacks only once getMethods() already returns the public and protected methods a class inherits, and mergeMetadata() added the parent's callbacks on top, so an inherited #[PostHydrate] or #[PreExtract] method was called twice. An overridden one ran as the child's version and then again as the parent's, because the parent's reflection method was invoked directly. The merge now resolves every callback to the method PHP would call on the child and keeps it once. An override runs as the child's version, also when it doesn't repeat the attribute. Private methods of the parent are not inherited and stay as they are. --- README.md | 4 ++ phpstan-baseline.neon | 6 ++ src/Metadata/AttributeMetadataFactory.php | 38 +++++++++++- tests/Unit/Fixture/ParentDtoWithHooks.php | 28 +++++++++ tests/Unit/MetadataHydratorTest.php | 74 +++++++++++++++++++++++ 5 files changed, 148 insertions(+), 2 deletions(-) create mode 100644 tests/Unit/Fixture/ParentDtoWithHooks.php diff --git a/README.md b/README.md index 85650d4d..b74b0fc3 100644 --- a/README.md +++ b/README.md @@ -609,6 +609,10 @@ readonly class Dto } ``` +> [!NOTE] +> Hooks of parent classes are called as well, each one once. If a child class overrides +> a hook method, only the child's version is called, with or without the attribute. + ### Events Another way to intervene in the extract and hydrate process is through events. diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index c417d53a..ad9537d7 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -222,6 +222,12 @@ parameters: count: 1 path: tests/Unit/Fixture/DtoWithHooks.php + - + message: '#^Method Patchlevel\\Hydrator\\Tests\\Unit\\Fixture\\ParentDtoWithHooks\:\:preExtract\(\) is unused\.$#' + identifier: method.unused + count: 1 + path: tests/Unit/Fixture/ParentDtoWithHooks.php + - message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:484\:\:postHydrate\(\) is unused\.$#' identifier: method.unused diff --git a/src/Metadata/AttributeMetadataFactory.php b/src/Metadata/AttributeMetadataFactory.php index 6c70208d..f0ae94ff 100644 --- a/src/Metadata/AttributeMetadataFactory.php +++ b/src/Metadata/AttributeMetadataFactory.php @@ -290,12 +290,46 @@ private function mergeMetadata(ClassMetadata $child, ClassMetadata $parent): Cla $child->reflection(), array_values($properties), $childDataSubjectIdField ?? $parentDataSubjectIdField, - array_merge($child->postHydrateCallbacks(), $parent->postHydrateCallbacks()), - array_merge($child->preExtractCallbacks(), $parent->preExtractCallbacks()), + $this->mergeCallbacks($child->reflection(), $child->postHydrateCallbacks(), $parent->postHydrateCallbacks()), + $this->mergeCallbacks($child->reflection(), $child->preExtractCallbacks(), $parent->preExtractCallbacks()), $child->lazy() ?? $parent->lazy(), ); } + /** + * Every callback is resolved to the method PHP calls on the child, so an inherited method + * shows up once and an overridden one runs as the child's version. Private methods are not + * inherited and stay as they are. + * + * @param ReflectionClass $child + * @param list $childCallbacks + * @param list $parentCallbacks + * + * @return list + */ + private function mergeCallbacks(ReflectionClass $child, array $childCallbacks, array $parentCallbacks): array + { + $callbacks = []; + + foreach (array_merge($childCallbacks, $parentCallbacks) as $callback) { + $method = $callback->reflection(); + + if (!$method->isPrivate()) { + $method = $child->getMethod($method->getName()); + } + + $key = $method->getDeclaringClass()->getName() . '::' . $method->getName(); + + if (array_key_exists($key, $callbacks)) { + continue; + } + + $callbacks[$key] = new CallbackMetadata($method); + } + + return array_values($callbacks); + } + /** @param ReflectionClass $reflectionClass */ private function getSubjectIdField(ReflectionClass $reflectionClass): string|null { diff --git a/tests/Unit/Fixture/ParentDtoWithHooks.php b/tests/Unit/Fixture/ParentDtoWithHooks.php new file mode 100644 index 00000000..c49f1c94 --- /dev/null +++ b/tests/Unit/Fixture/ParentDtoWithHooks.php @@ -0,0 +1,28 @@ + */ + #[Ignore] + public array $calls = []; + + #[PostHydrate] + protected function postHydrate(): void + { + $this->calls[] = 'parent postHydrate'; + } + + #[PreExtract] + private function preExtract(): void + { + $this->calls[] = 'parent preExtract'; + } +} diff --git a/tests/Unit/MetadataHydratorTest.php b/tests/Unit/MetadataHydratorTest.php index 5b32b604..d0114158 100644 --- a/tests/Unit/MetadataHydratorTest.php +++ b/tests/Unit/MetadataHydratorTest.php @@ -7,6 +7,8 @@ use DateTime; use DateTimeImmutable; use DateTimeZone; +use Patchlevel\Hydrator\Attribute\PostHydrate; +use Patchlevel\Hydrator\Attribute\PreExtract; use Patchlevel\Hydrator\CircularReference; use Patchlevel\Hydrator\ClassNotSupported; use Patchlevel\Hydrator\Cryptography\PayloadCryptographer; @@ -36,6 +38,7 @@ use Patchlevel\Hydrator\Tests\Unit\Fixture\LazyProfileCreated; use Patchlevel\Hydrator\Tests\Unit\Fixture\NormalizerInBaseClassDefinedDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\ParentDto; +use Patchlevel\Hydrator\Tests\Unit\Fixture\ParentDtoWithHooks; use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileCreated; use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileCreatedWithInlineNormalizer; use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileCreatedWithNormalizer; @@ -662,6 +665,77 @@ public function testHydrateWithHooks(): void self::assertEquals(false, $object->preExtractCalled); } + public function testInheritedHooksRunOnce(): void + { + $child = new class extends ParentDtoWithHooks { + }; + + $object = $this->hydrator->hydrate($child::class, []); + + self::assertSame(['parent postHydrate'], $object->calls); + + $this->hydrator->extract($object); + + self::assertSame(['parent postHydrate', 'parent preExtract'], $object->calls); + } + + public function testOverriddenHookRunsOnceAsChildVersion(): void + { + $child = new class extends ParentDtoWithHooks { + #[PostHydrate] + protected function postHydrate(): void + { + $this->calls[] = 'child postHydrate'; + } + }; + + $object = $this->hydrator->hydrate($child::class, []); + + self::assertSame(['child postHydrate'], $object->calls); + } + + public function testOverriddenHookWithoutAttributeRunsOnceAsChildVersion(): void + { + $child = new class extends ParentDtoWithHooks { + protected function postHydrate(): void + { + $this->calls[] = 'child postHydrate'; + } + }; + + $object = $this->hydrator->hydrate($child::class, []); + + self::assertSame(['child postHydrate'], $object->calls); + } + + public function testHooksOfParentAndChildRunOnceEach(): void + { + $child = new class extends ParentDtoWithHooks { + #[PostHydrate] + protected function childPostHydrate(): void + { + $this->calls[] = 'child postHydrate'; + } + + #[PreExtract] + protected function childPreExtract(): void + { + $this->calls[] = 'child preExtract'; + } + }; + + $object = $this->hydrator->hydrate($child::class, []); + + self::assertSame(['child postHydrate', 'parent postHydrate'], $object->calls); + + $this->hydrator->extract($object); + + self::assertSame( + ['child postHydrate', 'parent postHydrate', 'child preExtract', 'parent preExtract'], + $object->calls, + ); + } + #[RequiresPhp('>=8.4')] public function testLazyHydrate(): void { From f6e5de2b447f83202cf61cd8ba17d201b834e908 Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 20:21:26 +0100 Subject: [PATCH 7/9] Fix normalizer examples in the readme The array and array shape examples used #[ArrayNormalizer] and #[ArrayShapeNormalizer] without arguments, which fails because both constructors require the inner normalizers. In these cases the normalizer is inferred from the docblock, so the attribute is dropped and the text says so. A few other examples had typos that made them invalid PHP, like a misspelled class name, missing semicolons and a match arm written as a case. --- README.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index b74b0fc3..7e72b052 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,7 @@ Below you will find the list of all normalizers and how to set them manually or If you have a collection (array, iterable, list) with a data type that needs to be normalized, you can use the ArrayNormalizer and pass it the required normalizer. +If the type of the items is given in the docblock, the normalizer is inferred and no attribute is needed. ```php use Patchlevel\Hydrator\Normalizer\ArrayNormalizer; @@ -176,7 +177,6 @@ final class DTO /** * @var list */ - #[ArrayNormalizer] public array $dates; #[ArrayNormalizer(new DateTimeImmutableNormalizer())] @@ -189,7 +189,9 @@ final class DTO #### ArrayShape -If you have an array with a specific shape, you can use the `ArrayShapeNormalizer`. +If you have an array with a specific shape, you can use the `ArrayShapeNormalizer` +and pass it a map of field names to normalizers. +If the shape is given in the docblock, the normalizer is inferred and no attribute is needed. ```php use Patchlevel\Hydrator\Normalizer\ArrayShapeNormalizer; @@ -203,7 +205,6 @@ final class DTO * otherField: string * } */ - #[ArrayShapeNormalizer] public array $meta; #[ArrayShapeNormalizer(['date' => new DateTimeImmutableNormalizer()])] @@ -316,9 +317,9 @@ use Patchlevel\Hydrator\Normalizer\ObjectNormalizer; final class DTO { #[ObjectNormalizer] - public AnohterDto $anotherDto; + public AnotherDto $anotherDto; - #[ObjectNormalizer(AnohterDto::class)] + #[ObjectNormalizer(AnotherDto::class)] public object $object; } @@ -467,7 +468,7 @@ Now we can also use the normalizer directly. final class DTO { #[NameNormalizer] - public Name $name + public Name $name; } ``` @@ -497,7 +498,7 @@ class NameGuesser implements Guesser public function guess(ObjectType $object): Normalizer|null { return match($object->getClassName()) { - case Name::class => new NameNormalizer(), + Name::class => new NameNormalizer(), default => null, }; } @@ -526,7 +527,7 @@ use Patchlevel\Hydrator\Attribute\NormalizedName; final class DTO { #[NormalizedName('profile_name')] - public string $name + public string $name; } ``` From ae3efa5961ecef86b6136c88957ed9ad829f4e65 Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 21:24:41 +0100 Subject: [PATCH 8/9] Let the readme normalizer example handle null Normalizers get null for nullable properties and, since the array shape fix, for null values in shapes as well, so the example should not reject it. --- README.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7e72b052..3020101f 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ $event = $hydrator->hydrate( ] ); -$oldEvent == $event // true +$oldEvent == $event; // true ``` > [!WARNING] @@ -438,8 +438,12 @@ use Patchlevel\Hydrator\Normalizer\InvalidArgument; #[Attribute(Attribute::TARGET_PROPERTY | Attribute::TARGET_CLASS)] class NameNormalizer implements Normalizer { - public function normalize(mixed $value): string + public function normalize(mixed $value): ?string { + if ($value === null) { + return null; + } + if (!$value instanceof Name) { throw InvalidArgument::withWrongType(Name::class, $value); } From ee0c03aaa584aab2f2314da3706fc7a43fc2dfd0 Mon Sep 17 00:00:00 2001 From: David Badura Date: Sat, 7 Nov 2026 11:22:30 +0100 Subject: [PATCH 9/9] Document which array shape keys are converted --- docs/normalizer.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/normalizer.md b/docs/normalizer.md index 325befdb..59878374 100644 --- a/docs/normalizer.md +++ b/docs/normalizer.md @@ -80,6 +80,12 @@ final class Profile public array $explicitMeta; } ``` +:::note +Only the keys with a normalizer are converted. All other keys, including keys +that are not part of the shape, are kept as they are, so they must already hold +values that your storage can handle. A `null` value is passed to the normalizer +of its key, like for any other property. +::: ## DateTimeImmutable