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)) { diff --git a/docs/normalizer.md b/docs/normalizer.md index 5e0d27fe..dfc6103e 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` @@ -220,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/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" } ] } ] diff --git a/src/Metadata/AttributeMetadataFactory.php b/src/Metadata/AttributeMetadataFactory.php index b3d530d1..3f48f817 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), ); } @@ -219,10 +218,16 @@ 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) { + // 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; } @@ -278,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; @@ -309,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 23d99619..e90e6efb 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 @@ -105,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/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/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/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 @@ + '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 @@ + new EnumNormalizer(), + 'skill' => new ObjectNormalizer(Skill::class), + ])] + public array|null $shape = null, + ) { + } +} 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 @@ +, 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 @@ + $blocks */ + public function __construct( + public Block $block, + public ContentBlock $contentBlock, + public array $blocks, + public Shape $shape, + ) { + } +} diff --git a/tests/Unit/Fixture/PureEnum.php b/tests/Unit/Fixture/PureEnum.php new file mode 100644 index 00000000..31c4ab2b --- /dev/null +++ b/tests/Unit/Fixture/PureEnum.php @@ -0,0 +1,11 @@ + '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 @@ +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(); @@ -391,4 +434,80 @@ 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(); + $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/Normalizer/ArrayShapeNormalizerTest.php b/tests/Unit/Normalizer/ArrayShapeNormalizerTest.php index 78be01dc..c6024854 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 @@ -93,6 +97,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']; @@ -165,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/Normalizer/ObjectNormalizerTest.php b/tests/Unit/Normalizer/ObjectNormalizerTest.php index 6744f612..17b552a7 100644 --- a/tests/Unit/Normalizer/ObjectNormalizerTest.php +++ b/tests/Unit/Normalizer/ObjectNormalizerTest.php @@ -117,6 +117,27 @@ public function testDenormalizeWithValue(): void ); } + public function testDenormalizePassesNonArrayValueToHydrator(): void + { + $hydrator = $this->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 8b8e3195..85c9820e 100644 --- a/tests/Unit/StackHydratorTest.php +++ b/tests/Unit/StackHydratorTest.php @@ -25,18 +25,26 @@ 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\ExplicitObjectNormalizerDto; 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; @@ -44,8 +52,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; @@ -238,6 +249,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( @@ -557,6 +573,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 testHydrateWithClassNormalizer(): void { $object = $this->hydrator->hydrate( @@ -567,6 +651,126 @@ 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'), + ); + } + + 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]), + ); + } + + 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 {