diff --git a/docs/normalizer.md b/docs/normalizer.md index 023c702..dfc6103 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 67c7d41..3f48f81 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; @@ -28,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 @@ -166,26 +166,26 @@ 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, ); } @@ -193,11 +193,10 @@ private function mergeMetadata(ClassMetadata $parent, ClassMetadata $child): Cla } return new ClassMetadata( - $parent->reflection, + $child->reflection, $child->normalizer ?? $parent->normalizer, array_values($properties), $child->lazy ?? $parent->lazy, - array_merge($parent->extras, $child->extras), ); } @@ -225,7 +224,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; } @@ -281,21 +283,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; @@ -312,21 +300,7 @@ private function inferNormalizerByType(Type $type): Normalizer|null } if ($type instanceof CollectionType) { - $valueType = $type->getCollectionValueType(); - - if ($valueType instanceof NullableType) { - $valueType = $type->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/src/Normalizer/ArrayShapeNormalizer.php b/src/Normalizer/ArrayShapeNormalizer.php index 3a67a08..e90e6ef 100644 --- a/src/Normalizer/ArrayShapeNormalizer.php +++ b/src/Normalizer/ArrayShapeNormalizer.php @@ -102,7 +102,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/BaseId.php b/tests/Unit/Fixture/BaseId.php new file mode 100644 index 0000000..ec4e2d1 --- /dev/null +++ b/tests/Unit/Fixture/BaseId.php @@ -0,0 +1,23 @@ +id; + } +} diff --git a/tests/Unit/Fixture/BaseLazyDto.php b/tests/Unit/Fixture/BaseLazyDto.php new file mode 100644 index 0000000..9cc4a4e --- /dev/null +++ b/tests/Unit/Fixture/BaseLazyDto.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 0000000..d2fb2fa --- /dev/null +++ b/tests/Unit/Fixture/Circle.php @@ -0,0 +1,13 @@ + new EnumNormalizer(), + 'skill' => new ObjectNormalizer(Skill::class), + ])] + public array|null $shape = null, + ) { + } +} diff --git a/tests/Unit/Fixture/InferNormalizerWithNullableItemsDto.php b/tests/Unit/Fixture/InferNormalizerWithNullableItemsDto.php new file mode 100644 index 0000000..894e6c9 --- /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/Fixture/InferNormalizerWithNullableShapeItemsDto.php b/tests/Unit/Fixture/InferNormalizerWithNullableShapeItemsDto.php new file mode 100644 index 0000000..c49fb47 --- /dev/null +++ b/tests/Unit/Fixture/InferNormalizerWithNullableShapeItemsDto.php @@ -0,0 +1,14 @@ + $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 0000000..a5f2c7e --- /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 0000000..7976ef5 --- /dev/null +++ b/tests/Unit/Fixture/Square.php @@ -0,0 +1,13 @@ +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 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(); @@ -395,6 +435,43 @@ public function testClassMetadataWithNormalizer(): void self::assertInstanceOf(IdNormalizer::class, $metadata->normalizer); } + 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, + ); + } + + 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, + ); + } + public function testClassMetadataOfBackedEnumGetsEnumNormalizer(): void { $metadataFactory = new AttributeMetadataFactory(); diff --git a/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php b/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php index 156a89a..c602485 100644 --- a/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php +++ b/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php @@ -6,11 +6,15 @@ 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\TypeAwareNormalizer; +use Patchlevel\Hydrator\Tests\Unit\Fixture\Status; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +use Symfony\Component\TypeInfo\Type; #[CoversClass(ArrayShapeNormalizer::class)] final class ArrayShapeNormalizerTest extends TestCase @@ -231,6 +235,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 20512b2..fa93b9a 100644 --- a/tests/Unit/StackHydratorTest.php +++ b/tests/Unit/StackHydratorTest.php @@ -25,19 +25,25 @@ use Patchlevel\Hydrator\Normalizer\HydratorAwareNormalizer; use Patchlevel\Hydrator\StackHydrator; use Patchlevel\Hydrator\StackHydratorBuilder; +use Patchlevel\Hydrator\Tests\Unit\Fixture\Circle; use Patchlevel\Hydrator\Tests\Unit\Fixture\Circle1Dto; use Patchlevel\Hydrator\Tests\Unit\Fixture\Circle2Dto; use Patchlevel\Hydrator\Tests\Unit\Fixture\Circle3Dto; +use Patchlevel\Hydrator\Tests\Unit\Fixture\CodeBlock; +use Patchlevel\Hydrator\Tests\Unit\Fixture\ContentBlock; use Patchlevel\Hydrator\Tests\Unit\Fixture\ContextAwareDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\DefaultDto; 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\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\InferNormalizerWithNullableItemsDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\LazyProfileCreated; use Patchlevel\Hydrator\Tests\Unit\Fixture\NormalizerInBaseClassDefinedDto; +use Patchlevel\Hydrator\Tests\Unit\Fixture\ObjectMapDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\ParentDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileCreated; use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileCreatedWithInlineNormalizer; @@ -45,9 +51,11 @@ use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileCreatedWrapper; use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileId; use Patchlevel\Hydrator\Tests\Unit\Fixture\Skill; +use Patchlevel\Hydrator\Tests\Unit\Fixture\Square; 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; @@ -564,6 +572,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([ @@ -588,6 +619,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 testHydrateWithClassNormalizer(): void { $object = $this->hydrator->hydrate( @@ -618,6 +670,82 @@ 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( + new ContentBlock('foo'), + new ContentBlock('bar'), + [new ContentBlock('baz'), new CodeBlock('echo 1;')], + new Circle(5), + ); + + self::assertSame( + [ + 'block' => ['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 {