Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 8 additions & 36 deletions src/Metadata/AttributeMetadataFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,34 +166,34 @@ private function hasIgnore(ReflectionProperty $reflectionProperty): bool
}

/**
* @param ClassMetadata<T> $parent
* @param ClassMetadata<T> $child
*
* @return ClassMetadata<T>
*
* @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;
}

return new ClassMetadata(
$parent->reflection,
$child->reflection,
$child->normalizer ?? $parent->normalizer,
array_values($properties),
$child->lazy ?? $parent->lazy,
Expand Down Expand Up @@ -281,21 +281,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;
Expand All @@ -312,21 +298,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);
Expand Down
2 changes: 1 addition & 1 deletion src/Normalizer/ArrayShapeNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
12 changes: 12 additions & 0 deletions tests/Unit/Fixture/BaseLazyDto.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Tests\Unit\Fixture;

use Patchlevel\Hydrator\Attribute\Lazy;

#[Lazy]
abstract class BaseLazyDto
{
}
22 changes: 22 additions & 0 deletions tests/Unit/Fixture/ExplicitArrayShapeNormalizerDto.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Tests\Unit\Fixture;

use Patchlevel\Hydrator\Normalizer\ArrayShapeNormalizer;
use Patchlevel\Hydrator\Normalizer\EnumNormalizer;
use Patchlevel\Hydrator\Normalizer\ObjectNormalizer;

final class ExplicitArrayShapeNormalizerDto
{
/** @param array{status: Status}|null $shape */
public function __construct(
#[ArrayShapeNormalizer([
'status' => new EnumNormalizer(),
'skill' => new ObjectNormalizer(Skill::class),
])]
public array|null $shape = null,
) {
}
}
24 changes: 24 additions & 0 deletions tests/Unit/Fixture/InferNormalizerWithNullableItemsDto.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Tests\Unit\Fixture;

use DateTimeImmutable;

final class InferNormalizerWithNullableItemsDto
{
/**
* @param list<?Skill> $skills
* @param array<string, ?Status> $statuses
* @param list<DateTimeImmutable|null> $dates
* @param array<string, list<?Status>>|null $nested
*/
public function __construct(
public array $skills = [],
public array $statuses = [],
public array $dates = [],
public array|null $nested = null,
) {
}
}
14 changes: 14 additions & 0 deletions tests/Unit/Fixture/InferNormalizerWithNullableShapeItemsDto.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Tests\Unit\Fixture;

final class InferNormalizerWithNullableShapeItemsDto
{
/** @param array{skill: ?Skill, status: Status} $shape */
public function __construct(
public array $shape,
) {
}
}
67 changes: 67 additions & 0 deletions tests/Unit/Metadata/AttributeMetadataFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@
use Patchlevel\Hydrator\Metadata\ClassNotFound;
use Patchlevel\Hydrator\Metadata\DuplicatedFieldNameInMetadata;
use Patchlevel\Hydrator\Metadata\PropertyMetadataNotFound;
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;
Expand All @@ -21,10 +25,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\InferNormalizerWithNullableShapeItemsDto;
use Patchlevel\Hydrator\Tests\Unit\Fixture\ParentDto;
use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileCreatedWithGeneric;
use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileId;
use Patchlevel\Hydrator\Tests\Unit\Fixture\PureEnum;
use Patchlevel\Hydrator\Tests\Unit\Fixture\Skill;
use Patchlevel\Hydrator\Tests\Unit\Fixture\Status;
use Patchlevel\Hydrator\Tests\Unit\Fixture\StatusWithNormalizer;
use Patchlevel\Hydrator\Tests\Unit\Fixture\Wrapper;
Expand Down Expand Up @@ -395,6 +402,66 @@ public function testClassMetadataWithNormalizer(): void
self::assertInstanceOf(IdNormalizer::class, $metadata->normalizer);
}

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,
);
}

public function testClassMetadataOfBackedEnumGetsEnumNormalizer(): void
{
$metadataFactory = new AttributeMetadataFactory();
Expand Down
27 changes: 27 additions & 0 deletions tests/Unit/Normalizer/ArrayShapeNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down
46 changes: 46 additions & 0 deletions tests/Unit/StackHydratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@
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\ParentDto;
Expand Down Expand Up @@ -564,6 +566,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([
Expand All @@ -588,6 +613,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(
Expand Down
Loading