Skip to content

Commit

Permalink
feat(serializer): VersionMap attribute to add version for `Serializ…
Browse files Browse the repository at this point in the history
…able`.
  • Loading branch information
LastDragon-ru committed Nov 2, 2023
1 parent cafa2eb commit 5a22197
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
16 changes: 16 additions & 0 deletions packages/serializer/src/Attributes/VersionMap.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php declare(strict_types = 1);

namespace LastDragon_ru\LaraASP\Serializer\Attributes;

use Attribute;
use Symfony\Component\Serializer\Annotation\DiscriminatorMap;

#[Attribute(Attribute::TARGET_CLASS)]
class VersionMap extends DiscriminatorMap {
/**
* @param array<string, class-string> $mapping
*/
public function __construct(array $mapping) {
parent::__construct('$v', $mapping);
}
}
28 changes: 28 additions & 0 deletions packages/serializer/src/Metadata/MetadataFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace LastDragon_ru\LaraASP\Serializer\Metadata;

use JsonSerializable;
use LastDragon_ru\LaraASP\Serializer\Attributes\VersionMap;
use LastDragon_ru\LaraASP\Serializer\Testing\Package\TestCase;
use PHPUnit\Framework\Attributes\CoversClass;
use Symfony\Component\PropertyInfo\Type;
Expand All @@ -27,6 +28,7 @@ public function testGetMetadataFor(): void {
$factory = new MetadataFactory();
$a = $factory->getMetadataFor(MetadataFactoryTest_A::class);
$b = $factory->getMetadataFor(MetadataFactoryTest_B::class);
$c = $factory->getMetadataFor(MetadataFactoryTest_C::class);

self::assertEquals(
[
Expand Down Expand Up @@ -60,6 +62,19 @@ public function testGetMetadataFor(): void {
'mapping' => $b->getClassDiscriminatorMapping()?->getTypesMapping(),
],
);
self::assertEquals(
[
'property' => '$v',
'mapping' => [
'a' => MetadataFactoryTest_A::class,
'b' => MetadataFactoryTest_B::class,
],
],
[
'property' => $c->getClassDiscriminatorMapping()?->getTypeProperty(),
'mapping' => $c->getClassDiscriminatorMapping()?->getTypesMapping(),
],
);
}

public function testGetTypes(): void {
Expand Down Expand Up @@ -138,6 +153,10 @@ public function jsonSerialize(): mixed {
}
}

/**
* @internal
* @noinspection PhpMultipleClassesDeclarationsInOneFile
*/
class MetadataFactoryTest_B extends MetadataFactoryTest_A {
/**
* @phpstan-ignore-next-line required for tests
Expand All @@ -155,3 +174,12 @@ public function __construct(
// empty
}
}

/**
* @internal
* @noinspection PhpMultipleClassesDeclarationsInOneFile
*/
#[VersionMap(['b' => MetadataFactoryTest_B::class, 'a' => MetadataFactoryTest_A::class])]
class MetadataFactoryTest_C {
// empty
}

0 comments on commit 5a22197

Please sign in to comment.