Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add union object normalizer #40

Open
wants to merge 1 commit into
base: 1.3.x
Choose a base branch
from
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);

Check failure on line 32 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by PHPStan (locked, 8.3, ubuntu-latest)

Parameter #1 $array of function array_flip expects array<int|string>, array<class-string, string>|null given.

Check failure on line 32 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by Psalm (locked, 8.3, ubuntu-latest)

MixedPropertyTypeCoercion

src/Normalizer/UnionObjectNormalizer.php:32:33: MixedPropertyTypeCoercion: $this->typeToClassMap expects 'array<string, class-string>', parent type `array<array-key, array-key>` provided (see https://psalm.dev/196)

Check failure on line 32 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by Psalm (locked, 8.3, ubuntu-latest)

PossiblyNullArgument

src/Normalizer/UnionObjectNormalizer.php:32:44: PossiblyNullArgument: Argument 1 of array_flip cannot be null, possibly null value provided (see https://psalm.dev/078)
}

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

Check failure on line 52 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by PHPStan (locked, 8.3, ubuntu-latest)

Parameter #1 $array of function array_keys expects array, array<class-string, string>|null given.

Check failure on line 52 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by Psalm (locked, 8.3, ubuntu-latest)

PossiblyNullArgument

src/Normalizer/UnionObjectNormalizer.php:52:60: PossiblyNullArgument: Argument 1 of array_keys cannot be null, possibly null value provided (see https://psalm.dev/078)
$value,
);
}

if (!array_key_exists($value::class, $this->classToTypeMap)) {

Check failure on line 57 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by PHPStan (locked, 8.3, ubuntu-latest)

Parameter #2 $array of function array_key_exists expects array, array<class-string, string>|null given.

Check failure on line 57 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by Psalm (locked, 8.3, ubuntu-latest)

PossiblyNullArgument

src/Normalizer/UnionObjectNormalizer.php:57:46: PossiblyNullArgument: Argument 2 of array_key_exists cannot be null, possibly null value provided (see https://psalm.dev/078)
throw InvalidArgument::withWrongType(
sprintf('%s|null', implode('|', array_keys($this->classToTypeMap))),

Check failure on line 59 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by PHPStan (locked, 8.3, ubuntu-latest)

Parameter #1 $array of function array_keys expects array, array<class-string, string>|null given.

Check failure on line 59 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by Psalm (locked, 8.3, ubuntu-latest)

PossiblyNullArgument

src/Normalizer/UnionObjectNormalizer.php:59:60: PossiblyNullArgument: Argument 1 of array_keys cannot be null, possibly null value provided (see https://psalm.dev/078)
$value,
);
}

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

Check failure on line 65 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by Psalm (locked, 8.3, ubuntu-latest)

PossiblyNullArrayAccess

src/Normalizer/UnionObjectNormalizer.php:65:39: PossiblyNullArrayAccess: Cannot access array value on possibly null variable $this->classToTypeMap of type array<class-string, string>|null (see https://psalm.dev/079)

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{

Check failure on line 105 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by Psalm (locked, 8.3, ubuntu-latest)

MoreSpecificReturnType

src/Normalizer/UnionObjectNormalizer.php:105:16: MoreSpecificReturnType: The declared return type 'array{classToTypeMap: array<class-string, string>, hydrator: null, typeFieldName: string, typeToClassMap: array<string, class-string>}' for Patchlevel\Hydrator\Normalizer\UnionObjectNormalizer::__serialize is more specific than the inferred return type 'array{classToTypeMap: array<class-string, string>|null, hydrator: null, typeFieldName: string, typeToClassMap: array<string, class-string>}' (see https://psalm.dev/070)
* typeToClassMap: array<string, class-string>,
* classToTypeMap: array<class-string, string>,
* typeFieldName: string,
* hydrator: null
* }
*/
public function __serialize(): array
{
return [

Check failure on line 114 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by PHPStan (locked, 8.3, ubuntu-latest)

Method Patchlevel\Hydrator\Normalizer\UnionObjectNormalizer::__serialize() should return array{typeToClassMap: array<string, class-string>, classToTypeMap: array<class-string, string>, typeFieldName: string, hydrator: null} but returns array{typeToClassMap: array<string, class-string>, classToTypeMap: array<class-string, string>|null, typeFieldName: string, hydrator: null}.

Check failure on line 114 in src/Normalizer/UnionObjectNormalizer.php

View workflow job for this annotation

GitHub Actions / Static Analysis by Psalm (locked, 8.3, ubuntu-latest)

LessSpecificReturnStatement

src/Normalizer/UnionObjectNormalizer.php:114:16: LessSpecificReturnStatement: The type 'array{classToTypeMap: array<class-string, string>|null, hydrator: null, typeFieldName: string, typeToClassMap: array<string, class-string>}' is more general than the declared return type 'array{classToTypeMap: array<class-string, string>, hydrator: null, typeFieldName: string, typeToClassMap: array<string, class-string>}' for Patchlevel\Hydrator\Normalizer\UnionObjectNormalizer::__serialize (see https://psalm.dev/129)
'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);
}
}
Loading