From 38564c1dae7114ab209a2148c8ef249a603ad45d Mon Sep 17 00:00:00 2001 From: Konstantin Grachev Date: Fri, 20 Aug 2021 15:11:25 +0300 Subject: [PATCH] Add EnumNormalizer --- composer.json | 3 +- src/Symfony/EnumNormalizer.php | 51 ++++++++++++++++++++++++++++ tests/Symfony/EnumSerializerTest.php | 39 +++++++++++++++++++++ 3 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 src/Symfony/EnumNormalizer.php create mode 100644 tests/Symfony/EnumSerializerTest.php diff --git a/composer.json b/composer.json index b747f21..c71c6e3 100644 --- a/composer.json +++ b/composer.json @@ -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" } } diff --git a/src/Symfony/EnumNormalizer.php b/src/Symfony/EnumNormalizer.php new file mode 100644 index 0000000..76aa204 --- /dev/null +++ b/src/Symfony/EnumNormalizer.php @@ -0,0 +1,51 @@ +toId(); + } + + /** + * {@inheritdoc} + */ + public function supportsNormalization($data, string $format = null): bool + { + return $data instanceof Enum; + } +} diff --git a/tests/Symfony/EnumSerializerTest.php b/tests/Symfony/EnumSerializerTest.php new file mode 100644 index 0000000..472d3b2 --- /dev/null +++ b/tests/Symfony/EnumSerializerTest.php @@ -0,0 +1,39 @@ +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()]; + } +}