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
35 changes: 25 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ $event = $hydrator->hydrate(
]
);

$oldEvent == $event // true
$oldEvent == $event; // true
```

> [!WARNING]
Expand Down Expand Up @@ -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;
Expand All @@ -176,7 +177,6 @@ final class DTO
/**
* @var list<DateTimeImmutable>
*/
#[ArrayNormalizer]
public array $dates;

#[ArrayNormalizer(new DateTimeImmutableNormalizer())]
Expand All @@ -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;
Expand All @@ -203,14 +205,19 @@ final class DTO
* otherField: string
* }
*/
#[ArrayShapeNormalizer]
public array $meta;

#[ArrayShapeNormalizer(['date' => new DateTimeImmutableNormalizer()])]
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 `DateTimeImmutable` Normalizer, as the name suggests,
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -461,7 +472,7 @@ Now we can also use the normalizer directly.
final class DTO
{
#[NameNormalizer]
public Name $name
public Name $name;
}
```

Expand Down Expand Up @@ -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,
};
}
Expand Down Expand Up @@ -520,7 +531,7 @@ use Patchlevel\Hydrator\Attribute\NormalizedName;
final class DTO
{
#[NormalizedName('profile_name')]
public string $name
public string $name;
}
```

Expand Down Expand Up @@ -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.
Expand Down
16 changes: 11 additions & 5 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -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

-
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
92 changes: 49 additions & 43 deletions src/Metadata/AttributeMetadataFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -250,52 +250,86 @@
}

/**
* @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;
}

$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,

Check warning on line 292 in src/Metadata/AttributeMetadataFactory.php

View workflow job for this annotation

GitHub Actions / Mutation tests on diff (locked, 8.5, ubuntu-latest)

Escaped Mutant for Mutator "Coalesce": @@ @@ return new ClassMetadata( $child->reflection(), array_values($properties), - $childDataSubjectIdField ?? $parentDataSubjectIdField, + $parentDataSubjectIdField ?? $childDataSubjectIdField, $this->mergeCallbacks($child->reflection(), $child->postHydrateCallbacks(), $parent->postHydrateCallbacks()), $this->mergeCallbacks($child->reflection(), $child->preExtractCallbacks(), $parent->preExtractCallbacks()), $child->lazy() ?? $parent->lazy(),
$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<object> $child
* @param list<CallbackMetadata> $childCallbacks
* @param list<CallbackMetadata> $parentCallbacks
*
* @return list<CallbackMetadata>
*/
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();

Check warning on line 321 in src/Metadata/AttributeMetadataFactory.php

View workflow job for this annotation

GitHub Actions / Mutation tests on diff (locked, 8.5, ubuntu-latest)

Escaped Mutant for Mutator "ConcatOperandRemoval": @@ @@ $method = $child->getMethod($method->getName()); } - $key = $method->getDeclaringClass()->getName() . '::' . $method->getName(); + $key = $method->getDeclaringClass()->getName() . '::'; if (array_key_exists($key, $callbacks)) { continue;

Check warning on line 321 in src/Metadata/AttributeMetadataFactory.php

View workflow job for this annotation

GitHub Actions / Mutation tests on diff (locked, 8.5, ubuntu-latest)

Escaped Mutant for Mutator "Concat": @@ @@ $method = $child->getMethod($method->getName()); } - $key = $method->getDeclaringClass()->getName() . '::' . $method->getName(); + $key = $method->getDeclaringClass()->getName() . $method->getName() . '::'; if (array_key_exists($key, $callbacks)) { continue;

Check warning on line 321 in src/Metadata/AttributeMetadataFactory.php

View workflow job for this annotation

GitHub Actions / Mutation tests on diff (locked, 8.5, ubuntu-latest)

Escaped Mutant for Mutator "ConcatOperandRemoval": @@ @@ $method = $child->getMethod($method->getName()); } - $key = $method->getDeclaringClass()->getName() . '::' . $method->getName(); + $key = $method->getDeclaringClass()->getName() . $method->getName(); if (array_key_exists($key, $callbacks)) { continue;

Check warning on line 321 in src/Metadata/AttributeMetadataFactory.php

View workflow job for this annotation

GitHub Actions / Mutation tests on diff (locked, 8.5, ubuntu-latest)

Escaped Mutant for Mutator "ConcatOperandRemoval": @@ @@ $method = $child->getMethod($method->getName()); } - $key = $method->getDeclaringClass()->getName() . '::' . $method->getName(); + $key = '::' . $method->getName(); if (array_key_exists($key, $callbacks)) { continue;

Check warning on line 321 in src/Metadata/AttributeMetadataFactory.php

View workflow job for this annotation

GitHub Actions / Mutation tests on diff (locked, 8.5, ubuntu-latest)

Escaped Mutant for Mutator "Concat": @@ @@ $method = $child->getMethod($method->getName()); } - $key = $method->getDeclaringClass()->getName() . '::' . $method->getName(); + $key = '::' . $method->getDeclaringClass()->getName() . $method->getName(); if (array_key_exists($key, $callbacks)) { continue;

if (array_key_exists($key, $callbacks)) {
continue;

Check warning on line 324 in src/Metadata/AttributeMetadataFactory.php

View workflow job for this annotation

GitHub Actions / Mutation tests on diff (locked, 8.5, ubuntu-latest)

Escaped Mutant for Mutator "Continue_": @@ @@ $key = $method->getDeclaringClass()->getName() . '::' . $method->getName(); if (array_key_exists($key, $callbacks)) { - continue; + break; } $callbacks[$key] = new CallbackMetadata($method);
}

$callbacks[$key] = new CallbackMetadata($method);
}

return array_values($callbacks);
}

/** @param ReflectionClass<object> $reflectionClass */
private function getSubjectIdField(ReflectionClass $reflectionClass): string|null
{
Expand Down Expand Up @@ -419,21 +453,7 @@
$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 @@ -450,21 +470,7 @@
}

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
23 changes: 10 additions & 13 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,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;
}

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

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
{
}
Loading
Loading