Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
b4f5c04
Fix the file name of the 2.0 upgrade guide in the navigation
DavidBadura Oct 18, 2026
ee988b8
Merge pull request #234 from patchlevel/fix-upgrade-guide-link
DavidBadura Oct 18, 2026
f73f4ec
Keep the frontmatter of the docs when formatting the code
DavidBadura Oct 18, 2026
a431ae6
Merge pull request #235 from patchlevel/keep-docs-frontmatter
DavidBadura Oct 18, 2026
760de27
Use an enum type when looking up the class normalizer of an enum
DavidBadura Nov 6, 2026
8bb5042
Keep keys without a normalizer in array shapes
DavidBadura Nov 6, 2026
0fa034f
Merge pull request #241 from patchlevel/array-shape-keep-unmapped-keys
DavidBadura Nov 6, 2026
904bcf3
Merge pull request #240 from patchlevel/enum-class-normalizer
DavidBadura Nov 6, 2026
a5d840e
Keep keys without a normalizer in array shapes
DavidBadura Nov 6, 2026
026d804
Infer normalizers for nullable collection items
DavidBadura Nov 6, 2026
dc351f9
Skip array shape fields without type info in handleType
DavidBadura Nov 6, 2026
ef67f36
Let inferNormalizerByType unwrap collection and shape items itself
DavidBadura Nov 6, 2026
e3e8a10
Let the child class win when merging inherited metadata
DavidBadura Nov 6, 2026
90ac2f4
Run inherited lifecycle callbacks only once
DavidBadura Nov 6, 2026
f6e5de2
Fix normalizer examples in the readme
DavidBadura Nov 6, 2026
ae3efa5
Let the readme normalizer example handle null
DavidBadura Nov 6, 2026
25b84e5
Merge pull request #244 from patchlevel/normalizer-fixes-1x
DavidBadura Nov 6, 2026
c4a4019
Merge branch '2.0.x' into 1.24.x-merge-up-into-2.0.x_mxZsb44N
DavidBadura Nov 7, 2026
ee0c03a
Document which array shape keys are converted
DavidBadura Nov 7, 2026
b90b7c4
Merge pull request #245 from patchlevel/1.24.x-merge-up-into-2.0.x_mx…
DavidBadura Nov 7, 2026
1a71665
Merge branch '2.1.x' into 2.0.x-merge-up-into-2.1.x
DavidBadura Nov 7, 2026
e7ce0d9
Don't use the ObjectMapNormalizer as a class normalizer
DavidBadura Nov 6, 2026
36eaf21
Cover the child winning over its parent when merging metadata
DavidBadura Nov 6, 2026
9e296d8
Drop the extras merge from mergeMetadata
DavidBadura Nov 6, 2026
9ccfabd
Merge pull request #243 from patchlevel/object-map-class-normalizer
DavidBadura Nov 7, 2026
68fb733
Pass non-array values from ObjectNormalizer to the hydrator
DavidBadura Nov 6, 2026
092dae4
Merge pull request #239 from patchlevel/object-normalizer-class-norma…
DavidBadura Nov 7, 2026
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
11 changes: 11 additions & 0 deletions bin/docs-extract-php-code
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);

Expand Down
21 changes: 20 additions & 1 deletion bin/docs-inject-php-code
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -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)) {
Expand Down
12 changes: 12 additions & 0 deletions docs/normalizer.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
]
}
]
Expand Down
57 changes: 17 additions & 40 deletions src/Metadata/AttributeMetadataFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -166,38 +166,37 @@ 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,
array_merge($parent->extras, $child->extras),
);
}

Expand All @@ -219,10 +218,16 @@ private function getNormalizer(ReflectionProperty $reflectionProperty, Type $typ
/** @param ReflectionClass<object> $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;
}

Expand Down Expand Up @@ -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;
Expand All @@ -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);
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
6 changes: 0 additions & 6 deletions src/Normalizer/ObjectNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -56,10 +54,6 @@ public function denormalize(mixed $value, array $context): object|null
return null;
}

if (!is_array($value)) {
throw InvalidArgument::withWrongType('array<string, mixed>|null', $value);
}

$className = $this->className();

return $this->hydrator->hydrate($className, $value, $context);
Expand Down
23 changes: 23 additions & 0 deletions tests/Unit/Fixture/BaseId.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Tests\Unit\Fixture;

abstract class BaseId implements Id
{
final private function __construct(
private readonly string $id,
) {
}

public static function fromString(string $id): static
{
return new static($id);
}

public function toString(): string
{
return $this->id;
}
}
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
{
}
12 changes: 12 additions & 0 deletions tests/Unit/Fixture/Block.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\Normalizer\ObjectMapNormalizer;

#[ObjectMapNormalizer([ContentBlock::class => 'content', CodeBlock::class => 'code'])]
interface Block
{
}
13 changes: 13 additions & 0 deletions tests/Unit/Fixture/Circle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Tests\Unit\Fixture;

final class Circle extends Shape
{
public function __construct(
public int $radius,
) {
}
}
13 changes: 13 additions & 0 deletions tests/Unit/Fixture/CodeBlock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Tests\Unit\Fixture;

final class CodeBlock implements Block
{
public function __construct(
public string $code,
) {
}
}
13 changes: 13 additions & 0 deletions tests/Unit/Fixture/ContentBlock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Tests\Unit\Fixture;

final class ContentBlock implements Block
{
public function __construct(
public string $text,
) {
}
}
Loading
Loading