Skip to content
Open
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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,29 @@ final class AnotherDto
}
```

#### Union Object

If you have a union type from multiple classes, then you can use the `UnionObjectNormalizer` normalizer

```php
use Patchlevel\Hydrator\Normalizer\UnionObjectNormalizer;

final class DTO
{
#[UnionObjectNormalizer([
Foo::class => 'foo',
Bar::class => 'bar'
])]
public Foo|Bar|null $object;
}
```

> [!WARNING]
> Circular references are not supported and will result in an exception.

> [!NOTE]
> Auto detection of the type is not possible. You have to specify the type yourself.

### Custom Normalizer

Since we only offer normalizers for PHP native things,
Expand Down
7 changes: 6 additions & 1 deletion baseline.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<files psalm-version="5.22.2@d768d914152dbbf3486c36398802f74e80cfde48">
<files psalm-version="5.23.1@8471a896ccea3526b26d082f4461eeea467f10a4">
<file src="src/Normalizer/ObjectNormalizer.php">
<MixedArgument>
<code><![CDATA[$value]]></code>
Expand All @@ -8,4 +8,9 @@
<code><![CDATA[$value]]></code>
</MixedArgumentTypeCoercion>
</file>
<file src="src/Normalizer/UnionObjectNormalizer.php">
<MixedArgumentTypeCoercion>
<code><![CDATA[$value]]></code>
</MixedArgumentTypeCoercion>
</file>
</files>
121 changes: 121 additions & 0 deletions src/Normalizer/UnionObjectNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Normalizer;

use Attribute;
use Patchlevel\Hydrator\Hydrator;

use function array_flip;
use function array_key_exists;
use function array_keys;
use function implode;
use function is_array;
use function is_object;
use function is_string;
use function sprintf;

#[Attribute(Attribute::TARGET_PROPERTY)]
final class UnionObjectNormalizer implements Normalizer, HydratorAwareNormalizer
{
private Hydrator|null $hydrator = null;

/** @var array<string, class-string> */
private array $typeToClassMap;

/** @param array<class-string, string> $classToTypeMap */
public function __construct(
private readonly array|null $classToTypeMap = null,
private readonly string $typeFieldName = '_type',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's not the type but instead the type key right?

) {
$this->typeToClassMap = array_flip($classToTypeMap);
}

public function setHydrator(Hydrator $hydrator): void
{
$this->hydrator = $hydrator;
}

public function normalize(mixed $value): mixed
{
if (!$this->hydrator) {
throw new MissingHydrator();
}

if ($value === null) {
return null;
}

if (!is_object($value)) {
throw InvalidArgument::withWrongType(
sprintf('%s|null', implode('|', array_keys($this->classToTypeMap))),
$value,
);
}

if (!array_key_exists($value::class, $this->classToTypeMap)) {
throw InvalidArgument::withWrongType(
sprintf('%s|null', implode('|', array_keys($this->classToTypeMap))),
$value,
);
}

$data = $this->hydrator->extract($value);
$data[$this->typeFieldName] = $this->classToTypeMap[$value::class];

return $data;
}

public function denormalize(mixed $value): mixed
{
if (!$this->hydrator) {
throw new MissingHydrator();
}

if ($value === null) {
return null;
}

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

if (!array_key_exists($this->typeFieldName, $value)) {
throw new InvalidArgument(sprintf('missing type field "%s"', $this->typeFieldName));
}

$type = $value[$this->typeFieldName];

if (!is_string($type)) {
throw InvalidArgument::withWrongType('string', $type);
}

if (!array_key_exists($type, $this->typeToClassMap)) {
throw new InvalidArgument(sprintf('unknown type "%s"', $type));
}

$className = $this->typeToClassMap[$type];
unset($value[$this->typeFieldName]);

return $this->hydrator->hydrate($className, $value);
}

/**
* @return array{
* typeToClassMap: array<string, class-string>,
* classToTypeMap: array<class-string, string>,
* typeFieldName: string,
* hydrator: null
* }
*/
public function __serialize(): array
{
return [
'typeToClassMap' => $this->typeToClassMap,
'classToTypeMap' => $this->classToTypeMap,
'typeFieldName' => $this->typeFieldName,
'hydrator' => null,
];
}
}
143 changes: 143 additions & 0 deletions tests/Unit/Normalizer/UnionObjectNormalizerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Tests\Unit\Normalizer;

use Attribute;
use Patchlevel\Hydrator\Hydrator;
use Patchlevel\Hydrator\Normalizer\InvalidArgument;
use Patchlevel\Hydrator\Normalizer\MissingHydrator;
use Patchlevel\Hydrator\Normalizer\UnionObjectNormalizer;
use Patchlevel\Hydrator\Tests\Unit\Fixture\Email;
use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileCreated;
use Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileId;
use PHPUnit\Framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;

use function serialize;
use function unserialize;

#[Attribute(Attribute::TARGET_PROPERTY)]
final class UnionObjectNormalizerTest extends TestCase
{
use ProphecyTrait;

public function testNormalizeMissingHydrator(): void
{
$this->expectException(MissingHydrator::class);

$normalizer = new UnionObjectNormalizer([ProfileCreated::class => 'created']);
$this->assertEquals(null, $normalizer->normalize(null));
}

public function testDenormalizeMissingHydrator(): void
{
$this->expectException(MissingHydrator::class);

$normalizer = new UnionObjectNormalizer([ProfileCreated::class => 'created']);
$this->assertEquals(null, $normalizer->denormalize(null));
}

public function testNormalizeWithNull(): void
{
$hydrator = $this->prophesize(Hydrator::class);

$normalizer = new UnionObjectNormalizer([ProfileCreated::class => 'created']);
$normalizer->setHydrator($hydrator->reveal());

$this->assertEquals(null, $normalizer->normalize(null));
}

public function testDenormalizeWithNull(): void
{
$hydrator = $this->prophesize(Hydrator::class);

$normalizer = new UnionObjectNormalizer([ProfileCreated::class => 'created']);
$normalizer->setHydrator($hydrator->reveal());

$this->assertEquals(null, $normalizer->denormalize(null));
}

public function testNormalizeWithInvalidArgument(): void
{
$this->expectException(InvalidArgument::class);
$this->expectExceptionMessage('type "Patchlevel\Hydrator\Tests\Unit\Fixture\ProfileCreated|null" was expected but "string" was passed.');

$hydrator = $this->prophesize(Hydrator::class);

$normalizer = new UnionObjectNormalizer([ProfileCreated::class => 'created']);
$normalizer->setHydrator($hydrator->reveal());
$normalizer->normalize('foo');
}

public function testDenormalizeWithInvalidArgument(): void
{
$this->expectException(InvalidArgument::class);
$this->expectExceptionMessage('array<string, mixed>|null" was expected but "string" was passed.');

$hydrator = $this->prophesize(Hydrator::class);

$normalizer = new UnionObjectNormalizer([ProfileCreated::class => 'created']);
$normalizer->setHydrator($hydrator->reveal());
$normalizer->denormalize('foo');
}

public function testNormalizeWithValue(): void
{
$hydrator = $this->prophesize(Hydrator::class);

$event = new ProfileCreated(
ProfileId::fromString('1'),
Email::fromString('info@patchlevel.de'),
);

$hydrator->extract($event)
->willReturn(['profileId' => '1', 'email' => 'info@patchlevel.de'])
->shouldBeCalledOnce();

$normalizer = new UnionObjectNormalizer([ProfileCreated::class => 'created']);
$normalizer->setHydrator($hydrator->reveal());

self::assertEquals(
$normalizer->normalize($event),
['profileId' => '1', 'email' => 'info@patchlevel.de', '_type' => 'created'],
);
}

public function testDenormalizeWithValue(): void
{
$hydrator = $this->prophesize(Hydrator::class);

$expected = new ProfileCreated(
ProfileId::fromString('1'),
Email::fromString('info@patchlevel.de'),
);

$hydrator->hydrate(ProfileCreated::class, ['profileId' => '1', 'email' => 'info@patchlevel.de'])
->willReturn($expected)
->shouldBeCalledOnce();

$normalizer = new UnionObjectNormalizer([ProfileCreated::class => 'created']);
$normalizer->setHydrator($hydrator->reveal());

$this->assertEquals(
$expected,
$normalizer->denormalize(['profileId' => '1', 'email' => 'info@patchlevel.de', '_type' => 'created']),
);
}

public function testSerialize(): void
{
$hydrator = $this->prophesize(Hydrator::class);

$normalizer = new UnionObjectNormalizer([ProfileCreated::class => 'created']);
$normalizer->setHydrator($hydrator->reveal());

$serialized = serialize($normalizer);
$normalizer2 = unserialize($serialized);

self::assertInstanceOf(UnionObjectNormalizer::class, $normalizer2);
self::assertEquals(new UnionObjectNormalizer([ProfileCreated::class => 'created']), $normalizer2);
}
}