Skip to content

[Serializer] Add support of PHP backed enumerations #40830

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

Merged
merged 1 commit into from
Jul 5, 2021
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter;
use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer;
use Symfony\Component\Serializer\Normalizer\ConstraintViolationListNormalizer;
use Symfony\Component\Serializer\Normalizer\DataUriNormalizer;
use Symfony\Component\Serializer\Normalizer\DateIntervalNormalizer;
Expand Down Expand Up @@ -209,4 +210,11 @@
->args([service('request_stack'), param('kernel.debug')]),
])
;

if (interface_exists(\BackedEnum::class)) {
$container->services()
->set('serializer.normalizer.backed_enum', BackedEnumNormalizer::class)
->tag('serializer.normalizer', ['priority' => -915])
;
}
};
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"symfony/process": "^4.4|^5.0|^6.0",
"symfony/rate-limiter": "^5.2|^6.0",
"symfony/security-bundle": "^5.3|^6.0",
"symfony/serializer": "^5.2|^6.0",
"symfony/serializer": "^5.4|^6.0",
"symfony/stopwatch": "^4.4|^5.0|^6.0",
"symfony/string": "^5.0|^6.0",
"symfony/translation": "^5.3|^6.0",
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

5.4
---

* Add support of PHP backed enumerations

5.3
---

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Normalizer;

use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;

/**
* Normalizes a {@see \BackedEnum} enumeration to a string or an integer.
*
* @author Alexandre Daubois <alex.daubois@gmail.com>
*/
final class BackedEnumNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
{
/**
* {@inheritdoc}
*
* @throws InvalidArgumentException
*
* @return int|string
*/
public function normalize($object, $format = null, array $context = [])
{
if (!$object instanceof \BackedEnum) {
throw new InvalidArgumentException('The data must belong to a backed enumeration.');
}

return $object->value;
}

/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = null)
{
return $data instanceof \BackedEnum;
}

/**
* {@inheritdoc}
*
* @throws NotNormalizableValueException
*/
public function denormalize($data, $type, $format = null, array $context = [])
{
if (!is_subclass_of($type, \BackedEnum::class)) {
throw new InvalidArgumentException('The data must belong to a backed enumeration.');
}

if (!\is_int($data) && !\is_string($data)) {
throw new NotNormalizableValueException('The data is neither an integer nor a string, you should pass an integer or a string that can be parsed as an enumeration case of type '.$type.'.');
}

try {
return $type::from($data);
} catch (\ValueError $e) {
throw new NotNormalizableValueException($e->getMessage(), $e->getCode(), $e);
}
}

/**
* {@inheritdoc}
*/
public function supportsDenormalization($data, $type, $format = null)
{
return is_subclass_of($type, \BackedEnum::class);
}

/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool
{
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Symfony\Component\Serializer\Tests\Fixtures;

enum IntegerBackedEnumDummy: int
{
case SUCCESS = 200;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Symfony\Component\Serializer\Tests\Fixtures;

enum StringBackedEnumDummy: string
{
case GET = 'GET';
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Symfony\Component\Serializer\Tests\Fixtures;

enum UnitEnumDummy
{
case GET;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Tests\Normalizer;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Exception\InvalidArgumentException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer;
use Symfony\Component\Serializer\Tests\Fixtures\IntegerBackedEnumDummy;
use Symfony\Component\Serializer\Tests\Fixtures\StringBackedEnumDummy;
use Symfony\Component\Serializer\Tests\Fixtures\UnitEnumDummy;

/**
* @author Alexandre Daubois <alex.daubois@gmail.com>
*/
class BackedEnumNormalizerTest extends TestCase
{
/**
* @var BackedEnumNormalizer
*/
private $normalizer;

protected function setUp(): void
{
$this->normalizer = new BackedEnumNormalizer();
}

/**
* @requires PHP 8.1
*/
public function testSupportsNormalization()
{
$this->assertTrue($this->normalizer->supportsNormalization(StringBackedEnumDummy::GET));
$this->assertTrue($this->normalizer->supportsNormalization(IntegerBackedEnumDummy::SUCCESS));
$this->assertFalse($this->normalizer->supportsNormalization(UnitEnumDummy::GET));
$this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
}

/**
* @requires PHP 8.1
*/
public function testNormalize()
{
$this->assertSame('GET', $this->normalizer->normalize(StringBackedEnumDummy::GET));
$this->assertSame(200, $this->normalizer->normalize(IntegerBackedEnumDummy::SUCCESS));
}

/**
* @requires PHP 8.1
*/
public function testNormalizeBadObjectTypeThrowsException()
{
$this->expectException(InvalidArgumentException::class);
$this->normalizer->normalize(new \stdClass());
}

/**
* @requires PHP 8.1
*/
public function testSupportsDenormalization()
{
$this->assertTrue($this->normalizer->supportsDenormalization(null, StringBackedEnumDummy::class));
$this->assertTrue($this->normalizer->supportsDenormalization(null, IntegerBackedEnumDummy::class));
$this->assertFalse($this->normalizer->supportsDenormalization(null, UnitEnumDummy::class));
$this->assertFalse($this->normalizer->supportsDenormalization(null, \stdClass::class));
}

/**
* @requires PHP 8.1
*/
public function testDenormalize()
{
$this->assertSame(StringBackedEnumDummy::GET, $this->normalizer->denormalize('GET', StringBackedEnumDummy::class));
$this->assertSame(IntegerBackedEnumDummy::SUCCESS, $this->normalizer->denormalize(200, IntegerBackedEnumDummy::class));
}

/**
* @requires PHP 8.1
*/
public function testDenormalizeNullValueThrowsException()
{
$this->expectException(NotNormalizableValueException::class);
$this->normalizer->denormalize(null, StringBackedEnumDummy::class);
}

/**
* @requires PHP 8.1
*/
public function testDenormalizeBooleanValueThrowsException()
{
$this->expectException(NotNormalizableValueException::class);
$this->normalizer->denormalize(true, StringBackedEnumDummy::class);
}

/**
* @requires PHP 8.1
*/
public function testDenormalizeObjectThrowsException()
{
$this->expectException(NotNormalizableValueException::class);
$this->normalizer->denormalize(new \stdClass(), StringBackedEnumDummy::class);
}

/**
* @requires PHP 8.1
*/
public function testDenormalizeBadBackingValueThrowsException()
{
$this->expectException(NotNormalizableValueException::class);
$this->expectExceptionMessage('"POST" is not a valid backing value for enum "'.StringBackedEnumDummy::class.'"');
$this->normalizer->denormalize('POST', StringBackedEnumDummy::class);
}

public function testNormalizeShouldThrowExceptionForNonEnumObjects()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The data must belong to a backed enumeration.');

$this->normalizer->normalize(\stdClass::class);
}

public function testDenormalizeShouldThrowExceptionForNonEnumObjects()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The data must belong to a backed enumeration.');

$this->normalizer->denormalize('GET', \stdClass::class);
}

public function testSupportsNormalizationShouldFailOnAnyPHPVersionForNonEnumObjects()
{
$this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
}
}