From b4f5c0467fbb3ddb0cdfb5066cd10ed27fb70415 Mon Sep 17 00:00:00 2001 From: David Badura Date: Sun, 18 Oct 2026 19:36:15 +0200 Subject: [PATCH 01/17] Fix the file name of the 2.0 upgrade guide in the navigation --- docs/project.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/project.json b/docs/project.json index 66455feb..3effe9bc 100644 --- a/docs/project.json +++ b/docs/project.json @@ -25,7 +25,7 @@ { "title": "Miscellaneous", "subEntries": [ - { "title": "Upgrade from 1.x", "file": "UPGRADE-2.0md" } + { "title": "Upgrade from 1.x", "file": "UPGRADE-2.0.md" } ] } ] From f73f4ecd7f8c59820c250c81d7f16ed54bd2200a Mon Sep 17 00:00:00 2001 From: David Badura Date: Sun, 18 Oct 2026 19:36:43 +0200 Subject: [PATCH 02/17] Keep the frontmatter of the docs when formatting the code The docs scripts parse the pages with CommonMark, which rendered the frontmatter as a thematic break and a heading. They use the FrontMatterExtension now, the same way as the scripts of the event-sourcing repository. --- bin/docs-extract-php-code | 11 +++++++++++ bin/docs-inject-php-code | 21 ++++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/bin/docs-extract-php-code b/bin/docs-extract-php-code index d50b642d..a27094df 100755 --- a/bin/docs-extract-php-code +++ b/bin/docs-extract-php-code @@ -3,6 +3,8 @@ use League\CommonMark\Environment\Environment; use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode; +use League\CommonMark\Extension\FrontMatter\Data\FrontMatterDataParserInterface; +use League\CommonMark\Extension\FrontMatter\FrontMatterExtension; use League\CommonMark\Node\Query; use League\CommonMark\Parser\MarkdownParser; use Wnx\CommonmarkMarkdownRenderer\MarkdownRendererExtension; @@ -11,6 +13,15 @@ require __DIR__ . '/../vendor/autoload.php'; $environment = new Environment([]); $environment->addExtension(new MarkdownRendererExtension()); +$environment->addExtension(new FrontMatterExtension( + // keep the raw YAML string so it round-trips byte-identically + new class implements FrontMatterDataParserInterface { + public function parse(string $frontMatter): string + { + return $frontMatter; + } + }, +)); $parser = new MarkdownParser($environment); diff --git a/bin/docs-inject-php-code b/bin/docs-inject-php-code index e4e81ead..13694a10 100755 --- a/bin/docs-inject-php-code +++ b/bin/docs-inject-php-code @@ -3,6 +3,9 @@ use League\CommonMark\Environment\Environment; use League\CommonMark\Extension\CommonMark\Node\Block\FencedCode; +use League\CommonMark\Extension\FrontMatter\Data\FrontMatterDataParserInterface; +use League\CommonMark\Extension\FrontMatter\FrontMatterExtension; +use League\CommonMark\Extension\FrontMatter\Output\RenderedContentWithFrontMatter; use League\CommonMark\Node\Query; use League\CommonMark\Parser\MarkdownParser; use Wnx\CommonmarkMarkdownRenderer\MarkdownRendererExtension; @@ -14,6 +17,15 @@ require __DIR__ . '/../vendor/autoload.php'; $environment = new Environment([]); $environment->addExtension(new MarkdownRendererExtension()); +$environment->addExtension(new FrontMatterExtension( + // keep the raw YAML string so it round-trips byte-identically + new class implements FrontMatterDataParserInterface { + public function parse(string $frontMatter): string + { + return $frontMatter; + } + }, +)); $parser = new MarkdownParser($environment); $markdownRenderer = new MarkdownRenderer($environment); @@ -62,7 +74,14 @@ foreach ($finder as $file) { $node->setLiteral(trim($code)); } - file_put_contents($file->getPathname(), $markdownRenderer->renderDocument($document)); + $rendered = $markdownRenderer->renderDocument($document); + $output = $rendered->getContent(); + + if ($rendered instanceof RenderedContentWithFrontMatter) { + $output = $rendered->getFrontMatter() . "---\n" . $output; + } + + file_put_contents($file->getPathname(), $output); } if (file_exists($targetDir)) { From 760de2742d0fe78afb24ebd1b0355646c82b1c2e Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 18:40:09 +0100 Subject: [PATCH 03/17] Use an enum type when looking up the class normalizer of an enum getNormalizerOnClass always built the class type with Type::object(), so the guesser never saw a BackedEnumType for an enum class and never offered the EnumNormalizer. Extracting a backed enum directly gave its name and value, and hydrating it failed. An EnumNormalizer attribute without an explicit enum, on the enum or on an interface it implements, failed with a missing type for the same reason. The type is now built the way the type resolver builds it for a property of that class. An enum property with an explicit ObjectNormalizer also needs #239 to be hydrated again. --- src/Metadata/AttributeMetadataFactory.php | 5 ++- tests/Unit/Fixture/HasEnumNormalizer.php | 12 ++++++ tests/Unit/Fixture/PureEnum.php | 11 +++++ .../Fixture/StatusWithInterfaceNormalizer.php | 11 +++++ .../Metadata/AttributeMetadataFactoryTest.php | 42 +++++++++++++++++++ tests/Unit/StackHydratorTest.php | 26 ++++++++++++ 6 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 tests/Unit/Fixture/HasEnumNormalizer.php create mode 100644 tests/Unit/Fixture/PureEnum.php create mode 100644 tests/Unit/Fixture/StatusWithInterfaceNormalizer.php diff --git a/src/Metadata/AttributeMetadataFactory.php b/src/Metadata/AttributeMetadataFactory.php index b3d530d1..67c7d41a 100644 --- a/src/Metadata/AttributeMetadataFactory.php +++ b/src/Metadata/AttributeMetadataFactory.php @@ -219,7 +219,10 @@ private function getNormalizer(ReflectionProperty $reflectionProperty, Type $typ /** @param ReflectionClass $reflectionClass */ private function getNormalizerOnClass(ReflectionClass $reflectionClass): Normalizer|null { - $type = Type::object($reflectionClass->getName()); + // Build the type like the type resolver does for a property of this class, + // so enums get an enum type and the guesser can offer the EnumNormalizer. + $className = $reflectionClass->getName(); + $type = $reflectionClass->isEnum() ? Type::enum($className) : Type::object($className); $normalizer = $this->inferNormalizerByType($type); if ($normalizer instanceof ObjectNormalizer) { diff --git a/tests/Unit/Fixture/HasEnumNormalizer.php b/tests/Unit/Fixture/HasEnumNormalizer.php new file mode 100644 index 00000000..9a211849 --- /dev/null +++ b/tests/Unit/Fixture/HasEnumNormalizer.php @@ -0,0 +1,12 @@ +normalizer); } + + public function testClassMetadataOfBackedEnumGetsEnumNormalizer(): void + { + $metadataFactory = new AttributeMetadataFactory(); + $metadata = $metadataFactory->metadata(Status::class); + + self::assertEquals(new EnumNormalizer(Status::class), $metadata->normalizer); + } + + public function testClassMetadataOfBackedEnumWithEnumNormalizerAttribute(): void + { + $metadataFactory = new AttributeMetadataFactory(); + $metadata = $metadataFactory->metadata(StatusWithNormalizer::class); + + self::assertEquals(new EnumNormalizer(StatusWithNormalizer::class), $metadata->normalizer); + } + + public function testClassMetadataOfPureEnumHasNoNormalizer(): void + { + $metadataFactory = new AttributeMetadataFactory(); + $metadata = $metadataFactory->metadata(PureEnum::class); + + self::assertNull($metadata->normalizer); + } + + public function testGuesserGetsEnumTypeForEnumClass(): void + { + $guesser = $this->createMock(Guesser::class); + $guesser + ->expects(self::once()) + ->method('guess') + ->with(Type::enum(PureEnum::class)) + ->willReturn(null); + + $metadataFactory = new AttributeMetadataFactory(guesser: $guesser); + $metadata = $metadataFactory->metadata(PureEnum::class); + + self::assertNull($metadata->normalizer); + } } diff --git a/tests/Unit/StackHydratorTest.php b/tests/Unit/StackHydratorTest.php index 8b8e3195..162e9c1c 100644 --- a/tests/Unit/StackHydratorTest.php +++ b/tests/Unit/StackHydratorTest.php @@ -45,6 +45,7 @@ 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\StatusWithInterfaceNormalizer; use Patchlevel\Hydrator\Tests\Unit\Fixture\StatusWithNormalizer; use Patchlevel\Hydrator\Tests\Unit\Fixture\ValueObject; use Patchlevel\Hydrator\Tests\Unit\Fixture\WrongNormalizer; @@ -238,6 +239,11 @@ public function testExtractWithClassNormalizer(): void self::assertEquals('id', $data); } + public function testExtractBackedEnum(): void + { + self::assertSame('draft', $this->hydrator->extract(Status::Draft)); + } + public function testHydrate(): void { $expected = new ProfileCreated( @@ -567,6 +573,26 @@ public function testHydrateWithClassNormalizer(): void self::assertEquals(ProfileId::fromString('id'), $object); } + public function testHydrateBackedEnum(): void + { + self::assertSame(Status::Draft, $this->hydrator->hydrate(Status::class, 'draft')); + } + + public function testBackedEnumWithEnumNormalizerOnTheEnum(): void + { + self::assertSame('draft', $this->hydrator->extract(StatusWithNormalizer::Draft)); + self::assertSame(StatusWithNormalizer::Draft, $this->hydrator->hydrate(StatusWithNormalizer::class, 'draft')); + } + + public function testBackedEnumWithEnumNormalizerFromAnInterface(): void + { + self::assertSame('draft', $this->hydrator->extract(StatusWithInterfaceNormalizer::Draft)); + self::assertSame( + StatusWithInterfaceNormalizer::Draft, + $this->hydrator->hydrate(StatusWithInterfaceNormalizer::class, 'draft'), + ); + } + #[RequiresPhp('>=8.4')] public function testLazyHydrate(): void { From 8bb50422883f2860428e3d78698c5de37c8e0dc4 Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 18:39:13 +0100 Subject: [PATCH 04/17] 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. --- docs/normalizer.md | 7 ++ src/Normalizer/ArrayShapeNormalizer.php | 17 ++--- .../InferNormalizerWithArrayShapeDto.php | 16 +++++ .../Normalizer/ArrayShapeNormalizerTest.php | 66 +++++++++++++++++++ tests/Unit/StackHydratorTest.php | 25 +++++++ 5 files changed, 121 insertions(+), 10 deletions(-) create mode 100644 tests/Unit/Fixture/InferNormalizerWithArrayShapeDto.php diff --git a/docs/normalizer.md b/docs/normalizer.md index 5e0d27fe..023c702c 100644 --- a/docs/normalizer.md +++ b/docs/normalizer.md @@ -78,6 +78,13 @@ 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 With the `DateTimeImmutableNormalizer` you can convert `DateTimeImmutable` diff --git a/src/Normalizer/ArrayShapeNormalizer.php b/src/Normalizer/ArrayShapeNormalizer.php index 23d99619..3a67a084 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,17 +37,15 @@ 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; } - $result[$field] = $normalizer->normalize($value[$field], $context); + $value[$field] = $normalizer->normalize($value[$field], $context); } - return $result; + return $value; } /** @@ -64,17 +63,15 @@ 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; } - $result[$field] = $normalizer->denormalize($value[$field], $context); + $value[$field] = $normalizer->denormalize($value[$field], $context); } - 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/Normalizer/ArrayShapeNormalizerTest.php b/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php index 78be01dc..156a89a5 100644 --- a/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php +++ b/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php @@ -93,6 +93,72 @@ public function denormalize(mixed $value, array $context): 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 8b8e3195..61312367 100644 --- a/tests/Unit/StackHydratorTest.php +++ b/tests/Unit/StackHydratorTest.php @@ -33,6 +33,7 @@ use Patchlevel\Hydrator\Tests\Unit\Fixture\DummyMiddleware; 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; @@ -557,6 +558,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 testHydrateWithClassNormalizer(): void { $object = $this->hydrator->hydrate( From a5d840e0aabb5595c42e0371b7bf6819afa59d95 Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 19:57:40 +0100 Subject: [PATCH 05/17] 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 06/17] 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 07/17] 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 08/17] 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 09/17] 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 10/17] 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 11/17] 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 12/17] 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 13/17] 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 From e7ce0d9f13b22b85b475fe88b6cf0b148082cd4b Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 18:52:12 +0100 Subject: [PATCH 14/17] Don't use the ObjectMapNormalizer as a class normalizer The class normalizer lookup walks interfaces and parent classes, so a concrete class picked up a map declared on its interface or abstract parent as its own normalizer. The map calls extract() and hydrate() on that same class again, which made those classes impossible to extract or hydrate. Like the ObjectNormalizer, the map is now ignored on class level and only applies to properties. --- docs/normalizer.md | 5 ++ src/Metadata/AttributeMetadataFactory.php | 6 +- tests/Unit/Fixture/Block.php | 12 ++++ tests/Unit/Fixture/Circle.php | 13 ++++ tests/Unit/Fixture/CodeBlock.php | 13 ++++ tests/Unit/Fixture/ContentBlock.php | 13 ++++ tests/Unit/Fixture/ObjectMapDto.php | 17 ++++++ tests/Unit/Fixture/Shape.php | 12 ++++ tests/Unit/Fixture/Square.php | 13 ++++ tests/Unit/StackHydratorTest.php | 73 +++++++++++++++++++++++ 10 files changed, 176 insertions(+), 1 deletion(-) create mode 100644 tests/Unit/Fixture/Block.php create mode 100644 tests/Unit/Fixture/Circle.php create mode 100644 tests/Unit/Fixture/CodeBlock.php create mode 100644 tests/Unit/Fixture/ContentBlock.php create mode 100644 tests/Unit/Fixture/ObjectMapDto.php create mode 100644 tests/Unit/Fixture/Shape.php create mode 100644 tests/Unit/Fixture/Square.php diff --git a/docs/normalizer.md b/docs/normalizer.md index 023c702c..dfc6103e 100644 --- a/docs/normalizer.md +++ b/docs/normalizer.md @@ -227,6 +227,11 @@ final class Page :::note Auto detection of the concrete type is not possible here. You have to specify the map yourself. + +The map is only used for properties. Extracting a mapped class directly, e.g. +`$hydrator->extract($contentBlock)`, returns its plain fields without the type +field, and hydrating the interface itself at the top level, e.g. +`$hydrator->hydrate(Block::class, $data)`, is not supported. ::: ## Inline diff --git a/src/Metadata/AttributeMetadataFactory.php b/src/Metadata/AttributeMetadataFactory.php index ba764b5d..79385937 100644 --- a/src/Metadata/AttributeMetadataFactory.php +++ b/src/Metadata/AttributeMetadataFactory.php @@ -12,6 +12,7 @@ use Patchlevel\Hydrator\Normalizer\ArrayNormalizer; use Patchlevel\Hydrator\Normalizer\ArrayShapeNormalizer; use Patchlevel\Hydrator\Normalizer\Normalizer; +use Patchlevel\Hydrator\Normalizer\ObjectMapNormalizer; use Patchlevel\Hydrator\Normalizer\ObjectNormalizer; use Patchlevel\Hydrator\Normalizer\TypeAwareNormalizer; use ReflectionAttribute; @@ -225,7 +226,10 @@ private function getNormalizerOnClass(ReflectionClass $reflectionClass): Normali $type = $reflectionClass->isEnum() ? Type::enum($className) : Type::object($className); $normalizer = $this->inferNormalizerByType($type); - if ($normalizer instanceof ObjectNormalizer) { + // Both hand the object back to the hydrator. As class normalizer of a mapped class they + // would end in a recursion, and a map is only meant for properties typed as the + // interface or parent class that declares it. + if ($normalizer instanceof ObjectNormalizer || $normalizer instanceof ObjectMapNormalizer) { return null; } diff --git a/tests/Unit/Fixture/Block.php b/tests/Unit/Fixture/Block.php new file mode 100644 index 00000000..de9e35d8 --- /dev/null +++ b/tests/Unit/Fixture/Block.php @@ -0,0 +1,12 @@ + 'content', CodeBlock::class => 'code'])] +interface Block +{ +} diff --git a/tests/Unit/Fixture/Circle.php b/tests/Unit/Fixture/Circle.php new file mode 100644 index 00000000..d2fb2fa7 --- /dev/null +++ b/tests/Unit/Fixture/Circle.php @@ -0,0 +1,13 @@ + $blocks */ + public function __construct( + public Block $block, + public ContentBlock $contentBlock, + public array $blocks, + public Shape $shape, + ) { + } +} diff --git a/tests/Unit/Fixture/Shape.php b/tests/Unit/Fixture/Shape.php new file mode 100644 index 00000000..a5f2c7e4 --- /dev/null +++ b/tests/Unit/Fixture/Shape.php @@ -0,0 +1,12 @@ + 'circle', Square::class => 'square'])] +abstract class Shape +{ +} diff --git a/tests/Unit/Fixture/Square.php b/tests/Unit/Fixture/Square.php new file mode 100644 index 00000000..7976ef59 --- /dev/null +++ b/tests/Unit/Fixture/Square.php @@ -0,0 +1,13 @@ + ['text' => 'foo', '_type' => 'content'], + 'contentBlock' => ['text' => 'bar', '_type' => 'content'], + 'blocks' => [ + ['text' => 'baz', '_type' => 'content'], + ['code' => 'echo 1;', '_type' => 'code'], + ], + 'shape' => ['radius' => 5, '_type' => 'circle'], + ], + $this->hydrator->extract($object), + ); + } + + public function testHydrateWithObjectMapOnInterfaceAndAbstractClass(): void + { + $object = $this->hydrator->hydrate( + ObjectMapDto::class, + [ + 'block' => ['_type' => 'code', 'code' => 'echo 1;'], + 'contentBlock' => ['_type' => 'content', 'text' => 'bar'], + 'blocks' => [ + ['_type' => 'content', 'text' => 'baz'], + ['_type' => 'code', 'code' => 'echo 2;'], + ], + 'shape' => ['_type' => 'square', 'size' => 3], + ], + ); + + self::assertEquals( + new ObjectMapDto( + new CodeBlock('echo 1;'), + new ContentBlock('bar'), + [new ContentBlock('baz'), new CodeBlock('echo 2;')], + new Square(3), + ), + $object, + ); + } + + public function testExtractClassOfObjectMap(): void + { + self::assertSame(['text' => 'foo'], $this->hydrator->extract(new ContentBlock('foo'))); + self::assertSame(['radius' => 5], $this->hydrator->extract(new Circle(5))); + } + + public function testHydrateClassOfObjectMap(): void + { + self::assertEquals( + new ContentBlock('foo'), + $this->hydrator->hydrate(ContentBlock::class, ['text' => 'foo']), + ); + + self::assertEquals( + new Circle(5), + $this->hydrator->hydrate(Circle::class, ['radius' => 5]), + ); + } + #[RequiresPhp('>=8.4')] public function testLazyHydrate(): void { From 36eaf21000664db3cc74bba70e15f99eef89e65c Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 18:54:07 +0100 Subject: [PATCH 15/17] Cover the child winning over its parent when merging metadata The parameter fix itself came with the 1.24.4 merge-up. These tests pin it for 2.x, where it also decides the class normalizer: a class extending an abstract class that implements an interface with a class normalizer gets the normalizer bound to itself and can be hydrated. --- tests/Unit/Fixture/BaseId.php | 23 ++++++++++++++++ tests/Unit/Fixture/SubId.php | 9 +++++++ .../Metadata/AttributeMetadataFactoryTest.php | 26 +++++++++++++------ tests/Unit/StackHydratorTest.php | 9 +++++++ 4 files changed, 59 insertions(+), 8 deletions(-) create mode 100644 tests/Unit/Fixture/BaseId.php create mode 100644 tests/Unit/Fixture/SubId.php diff --git a/tests/Unit/Fixture/BaseId.php b/tests/Unit/Fixture/BaseId.php new file mode 100644 index 00000000..ec4e2d11 --- /dev/null +++ b/tests/Unit/Fixture/BaseId.php @@ -0,0 +1,23 @@ +id; + } +} diff --git a/tests/Unit/Fixture/SubId.php b/tests/Unit/Fixture/SubId.php new file mode 100644 index 00000000..1e9fd216 --- /dev/null +++ b/tests/Unit/Fixture/SubId.php @@ -0,0 +1,9 @@ +lazy); } - public function testClassMetadataWithNormalizer(): void - { - $metadataFactory = new AttributeMetadataFactory(); - $metadata = $metadataFactory->metadata(ProfileId::class); - - self::assertInstanceOf(IdNormalizer::class, $metadata->normalizer); - } - public function testLazyIsInheritedFromParent(): void { $object = new class extends BaseLazyDto { @@ -425,6 +418,23 @@ class extends BaseLazyDto { self::assertFalse($metadata->lazy); } + public function testClassNormalizerOfChildWinsOverParent(): void + { + $metadataFactory = new AttributeMetadataFactory(); + $metadata = $metadataFactory->metadata(SubId::class); + + self::assertInstanceOf(IdNormalizer::class, $metadata->normalizer); + self::assertSame(SubId::class, $metadata->normalizer->idClass()); + } + + public function testClassMetadataWithNormalizer(): void + { + $metadataFactory = new AttributeMetadataFactory(); + $metadata = $metadataFactory->metadata(ProfileId::class); + + self::assertInstanceOf(IdNormalizer::class, $metadata->normalizer); + } + public function testInferNormalizerForNullableCollectionItems(): void { $metadataFactory = new AttributeMetadataFactory(); diff --git a/tests/Unit/StackHydratorTest.php b/tests/Unit/StackHydratorTest.php index 86b1d223..fa93b9a6 100644 --- a/tests/Unit/StackHydratorTest.php +++ b/tests/Unit/StackHydratorTest.php @@ -55,6 +55,7 @@ use Patchlevel\Hydrator\Tests\Unit\Fixture\Status; use Patchlevel\Hydrator\Tests\Unit\Fixture\StatusWithInterfaceNormalizer; use Patchlevel\Hydrator\Tests\Unit\Fixture\StatusWithNormalizer; +use Patchlevel\Hydrator\Tests\Unit\Fixture\SubId; use Patchlevel\Hydrator\Tests\Unit\Fixture\ValueObject; use Patchlevel\Hydrator\Tests\Unit\Fixture\WrongNormalizer; use Patchlevel\Hydrator\TypeMismatch; @@ -669,6 +670,14 @@ public function testBackedEnumWithEnumNormalizerFromAnInterface(): void ); } + public function testRoundTripWithClassNormalizerFromAbstractParent(): void + { + $data = $this->hydrator->extract(SubId::fromString('1')); + + self::assertSame('1', $data); + self::assertEquals(SubId::fromString('1'), $this->hydrator->hydrate(SubId::class, $data)); + } + public function testExtractWithObjectMapOnInterfaceAndAbstractClass(): void { $object = new ObjectMapDto( From 9e296d842c0648f59fd32fc46fa8e7578e2b0533 Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 19:06:12 +0100 Subject: [PATCH 16/17] Drop the extras merge from mergeMetadata The factory never sets extras, enrichers only run on the final metadata, so both sides of the merge were always empty. --- src/Metadata/AttributeMetadataFactory.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Metadata/AttributeMetadataFactory.php b/src/Metadata/AttributeMetadataFactory.php index 79385937..3f48f817 100644 --- a/src/Metadata/AttributeMetadataFactory.php +++ b/src/Metadata/AttributeMetadataFactory.php @@ -29,7 +29,6 @@ use Symfony\Component\TypeInfo\TypeResolver\TypeResolver; use function array_key_exists; -use function array_merge; use function array_values; final class AttributeMetadataFactory implements MetadataFactory @@ -198,7 +197,6 @@ private function mergeMetadata(ClassMetadata $child, ClassMetadata $parent): Cla $child->normalizer ?? $parent->normalizer, array_values($properties), $child->lazy ?? $parent->lazy, - array_merge($parent->extras, $child->extras), ); } From 68fb7332b3339553fcc96234ea0325a31e37263b Mon Sep 17 00:00:00 2001 From: David Badura Date: Fri, 6 Nov 2026 18:21:51 +0100 Subject: [PATCH 17/17] Pass non-array values from ObjectNormalizer to the hydrator Extracting an object applies its class normalizer, so the result can be a scalar, but denormalize rejected everything that was not an array. Such a property could be written but never read back. Now the hydrator decides: it uses the class normalizer or throws ArrayDataRequired if there is none. --- src/Normalizer/ObjectNormalizer.php | 6 ----- .../Fixture/ExplicitObjectNormalizerDto.php | 16 ++++++++++++ .../Unit/Normalizer/ObjectNormalizerTest.php | 21 ++++++++++++++++ tests/Unit/StackHydratorTest.php | 25 +++++++++++++++++++ 4 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 tests/Unit/Fixture/ExplicitObjectNormalizerDto.php diff --git a/src/Normalizer/ObjectNormalizer.php b/src/Normalizer/ObjectNormalizer.php index f254b359..c6f654e3 100644 --- a/src/Normalizer/ObjectNormalizer.php +++ b/src/Normalizer/ObjectNormalizer.php @@ -12,8 +12,6 @@ use Symfony\Component\TypeInfo\Type\ObjectType; use Symfony\Component\TypeInfo\Type\TemplateType; -use function is_array; - #[Attribute(Attribute::TARGET_PROPERTY | Attribute::TARGET_CLASS)] final class ObjectNormalizer implements Normalizer, TypeAwareNormalizer, HydratorAwareNormalizer { @@ -56,10 +54,6 @@ public function denormalize(mixed $value, array $context): object|null return null; } - if (!is_array($value)) { - throw InvalidArgument::withWrongType('array|null', $value); - } - $className = $this->className(); return $this->hydrator->hydrate($className, $value, $context); diff --git a/tests/Unit/Fixture/ExplicitObjectNormalizerDto.php b/tests/Unit/Fixture/ExplicitObjectNormalizerDto.php new file mode 100644 index 00000000..c8489e01 --- /dev/null +++ b/tests/Unit/Fixture/ExplicitObjectNormalizerDto.php @@ -0,0 +1,16 @@ +createMock(Hydrator::class); + + $expected = ProfileId::fromString('1'); + + $hydrator->expects($this->once())->method('hydrate')->with( + ProfileId::class, + '1', + ) + ->willReturn($expected); + + $normalizer = new ObjectNormalizer(ProfileId::class); + $normalizer->setHydrator($hydrator); + + $this->assertEquals( + $expected, + $normalizer->denormalize('1', []), + ); + } + public function testNormalizePassesContextToHydrator(): void { $context = ['key' => 'value']; diff --git a/tests/Unit/StackHydratorTest.php b/tests/Unit/StackHydratorTest.php index fa93b9a6..85c9820e 100644 --- a/tests/Unit/StackHydratorTest.php +++ b/tests/Unit/StackHydratorTest.php @@ -36,6 +36,7 @@ use Patchlevel\Hydrator\Tests\Unit\Fixture\DummyMiddleware; use Patchlevel\Hydrator\Tests\Unit\Fixture\Email; use Patchlevel\Hydrator\Tests\Unit\Fixture\ExplicitArrayShapeNormalizerDto; +use Patchlevel\Hydrator\Tests\Unit\Fixture\ExplicitObjectNormalizerDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithArrayShapeDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\InferNormalizerWithIterablesDto; @@ -746,6 +747,30 @@ public function testHydrateClassOfObjectMap(): void ); } + public function testRoundTripWithExplicitObjectNormalizerAndClassNormalizer(): void + { + $object = new ExplicitObjectNormalizerDto(ProfileId::fromString('1')); + + $data = $this->hydrator->extract($object); + + self::assertEquals(['profileId' => '1'], $data); + self::assertEquals($object, $this->hydrator->hydrate(ExplicitObjectNormalizerDto::class, $data)); + } + + public function testHydrateWithExplicitObjectNormalizerAndNonArrayData(): void + { + try { + $this->hydrator->hydrate( + ProfileCreatedWrapper::class, + ['event' => 'foo'], + ); + + self::fail('DenormalizationFailure was not thrown'); + } catch (DenormalizationFailure $e) { + self::assertInstanceOf(ArrayDataRequired::class, $e->getPrevious()); + } + } + #[RequiresPhp('>=8.4')] public function testLazyHydrate(): void {