diff --git a/README.md b/README.md index d5081c3c..3020101f 100644 --- a/README.md +++ b/README.md @@ -119,7 +119,7 @@ $event = $hydrator->hydrate( ] ); -$oldEvent == $event // true +$oldEvent == $event; // true ``` > [!WARNING] @@ -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()])] @@ -211,6 +212,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, @@ -310,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; } @@ -431,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); } @@ -461,7 +472,7 @@ Now we can also use the normalizer directly. final class DTO { #[NameNormalizer] - public Name $name + public Name $name; } ``` @@ -491,7 +502,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, }; } @@ -520,7 +531,7 @@ use Patchlevel\Hydrator\Attribute\NormalizedName; final class DTO { #[NormalizedName('profile_name')] - public string $name + public string $name; } ``` @@ -603,6 +614,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 c012db30..ad9537d7 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,19 @@ parameters: path: tests/Unit/Fixture/DtoWithHooks.php - - message: '#^Method class@anonymous/tests/Unit/Metadata/AttributeMetadataFactoryTest\.php\:477\:\:postHydrate\(\) is unused\.$#' + 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 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\:484\:\:preExtract\(\) is unused\.$#' identifier: method.unused count: 1 path: tests/Unit/Metadata/AttributeMetadataFactoryTest.php @@ -241,13 +247,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\: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\:505\:\: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 7a13d505..f0ae94ff 100644 --- a/src/Metadata/AttributeMetadataFactory.php +++ b/src/Metadata/AttributeMetadataFactory.php @@ -250,52 +250,86 @@ 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, + $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 { @@ -419,21 +453,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 +470,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 ef517b6a..967ee490 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 @@ -113,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/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 @@ + new EnumNormalizer(), + 'skill' => new ObjectNormalizer(Skill::class), + ])] + public array|null $shape = null, + ) { + } +} 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/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/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 @@ + */ + #[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/Metadata/AttributeMetadataFactoryTest.php b/tests/Unit/Metadata/AttributeMetadataFactoryTest.php index 149a6b60..23604905 100644 --- a/tests/Unit/Metadata/AttributeMetadataFactoryTest.php +++ b/tests/Unit/Metadata/AttributeMetadataFactoryTest.php @@ -17,8 +17,12 @@ use Patchlevel\Hydrator\Metadata\MultipleDataSubjectId; use Patchlevel\Hydrator\Metadata\PropertyMetadataNotFound; use Patchlevel\Hydrator\Metadata\SubjectIdAndPersonalDataConflict; +use Patchlevel\Hydrator\Normalizer\ArrayNormalizer; +use Patchlevel\Hydrator\Normalizer\ArrayShapeNormalizer; +use Patchlevel\Hydrator\Normalizer\DateTimeImmutableNormalizer; use Patchlevel\Hydrator\Normalizer\EnumNormalizer; use Patchlevel\Hydrator\Normalizer\ObjectNormalizer; +use Patchlevel\Hydrator\Tests\Unit\Fixture\BaseLazyDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\BrokenParentDto; use Patchlevel\Hydrator\Tests\Unit\Fixture\DistributionCreated; use Patchlevel\Hydrator\Tests\Unit\Fixture\DuplicateFieldNameDto; @@ -27,11 +31,14 @@ 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\InferNormalizerWithNullableShapeItemsDto; 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 +550,64 @@ class { self::assertTrue($metadata->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(); + $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, + ); + } } diff --git a/tests/Unit/MetadataHydratorTest.php b/tests/Unit/MetadataHydratorTest.php index 88b66a77..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; @@ -26,13 +28,17 @@ 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; 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; +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; @@ -572,6 +578,74 @@ 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([ + '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 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); @@ -591,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 { diff --git a/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php b/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php index a85a6e44..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 @@ -90,6 +94,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']; @@ -162,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 4ec1fcb0..34e17cfb 100644 --- a/tests/Unit/StackHydratorTest.php +++ b/tests/Unit/StackHydratorTest.php @@ -26,9 +26,12 @@ 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; 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; @@ -500,6 +503,74 @@ 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([ + '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 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 {