Skip to content

Commit

Permalink
Add EnumNormalizer
Browse files Browse the repository at this point in the history
  • Loading branch information
grachevko committed Aug 20, 2021
1 parent 7313802 commit 38564c1
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 1 deletion.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"vimeo/psalm": "^4.9",
"phpstan/phpstan-strict-rules": "^0.12.10",
"phpstan/phpstan-phpunit": "^0.12.22",
"doctrine/dbal": "^2"
"doctrine/dbal": "^2",
"symfony/serializer": "^5.3"
}
}
51 changes: 51 additions & 0 deletions src/Symfony/EnumNormalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

namespace Premier\Enum\Symfony;

use Premier\Enum\Enum;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use function is_int;
use function is_subclass_of;

final class EnumNormalizer implements NormalizerInterface, DenormalizerInterface
{
/**
* {@inheritdoc}
*/
public function denormalize($data, string $type, string $format = null, array $context = []): Enum
{
/** @var callable $callable */
$callable = [$type, 'create'];

return $callable($data);
}

/**
* {@inheritdoc}
*/
public function supportsDenormalization($data, string $type, string $format = null): bool
{
return is_int($data) && is_subclass_of($type, Enum::class);
}

/**
* {@inheritdoc}
*/
public function normalize($object, string $format = null, array $context = []): int
{
/** @var Enum $object */

return $object->toId();
}

/**
* {@inheritdoc}
*/
public function supportsNormalization($data, string $format = null): bool
{
return $data instanceof Enum;
}
}
39 changes: 39 additions & 0 deletions tests/Symfony/EnumSerializerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

declare(strict_types=1);

namespace Premier\Enum\Tests\Symfony;

use PHPUnit\Framework\TestCase;
use Premier\Enum\Enum;
use Premier\Enum\Gender;
use Premier\Enum\Symfony\EnumNormalizer;
use Generator;

final class EnumSerializerTest extends TestCase
{
/**
* @dataProvider enums
*/
public function testNormalize(Enum $enum, int $expected): void
{
self::assertSame($expected, (new EnumNormalizer())->normalize($enum));
}

/**
* @dataProvider enums
*/
public function testDenormalize(Enum $expected, int $data): void
{
self::assertSame($expected, (new EnumNormalizer())->denormalize($data, $expected::class));
}

public function enums(): Generator
{
$male = Gender::male();
$female = Gender::female();

yield [$male, $male->toId()];
yield [$female, $female->toId()];
}
}

0 comments on commit 38564c1

Please sign in to comment.