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
6 changes: 6 additions & 0 deletions docs/normalizer.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ final class Profile
public array $explicitMeta;
}
```
:::note
Only the keys with a normalizer are converted. All other keys, including keys
that are not part of the shape, are kept as they are, so they must already hold
values that your storage can handle. A `null` value is passed to the normalizer
of its key, like for any other property.
:::

## DateTimeImmutable

Expand Down
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 @@ -278,21 +278,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 @@ -309,21 +295,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
19 changes: 8 additions & 11 deletions src/Normalizer/ArrayShapeNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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;
}

/**
Expand All @@ -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
Expand Down Expand Up @@ -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;
}

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,
) {
}
}
16 changes: 16 additions & 0 deletions tests/Unit/Fixture/InferNormalizerWithArrayShapeDto.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Tests\Unit\Fixture;

use DateTimeImmutable;

final class InferNormalizerWithArrayShapeDto
{
/** @param array{height: int, nickname: string|null, skills: list<Skill>, status: Status|null, createdAt: DateTimeImmutable} $profile */
public function __construct(
public array $profile,
) {
}
}
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 @@ -10,8 +10,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 @@ -20,9 +24,12 @@
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\Skill;
use Patchlevel\Hydrator\Tests\Unit\Fixture\Status;
use Patchlevel\Hydrator\Tests\Unit\Fixture\Wrapper;
use PHPUnit\Framework\Attributes\CoversClass;
Expand Down Expand Up @@ -391,4 +398,64 @@ 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,
);
}
}
Loading
Loading