Skip to content

[Serializer] Add BackedEnumNormalizer #40831

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

Closed
wants to merge 2 commits into from
Closed
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
1 change: 1 addition & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ CHANGELOG
* Add normalization formats to `UidNormalizer`
* Add `CsvEncoder::END_OF_LINE` context option
* Deprecate creating instances of the annotation classes by passing an array of parameters, use named arguments instead
* Added `BackedEnumNormalizer`

5.2.0
-----
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?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\NotNormalizableValueException;

final class BackedEnumNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
{
/**
* {@inheritdoc}
*
* @param \BackedEnum $object
*/
public function normalize($object, string $format = null, array $context = [])
{
return $object->value;
}

/**
* {@inheritdoc}
*/
public function supportsNormalization($data, string $format = null)
{
if (version_compare(\PHP_VERSION, '8.1', '<')) {
return false;
}

return $data instanceof \BackedEnum;
}

/**
* {@inheritdoc}
*/
public function denormalize($data, string $type, string $format = null, array $context = [])
{
$denormalized = $type::tryFrom($data);

if (null === $denormalized) {
throw new NotNormalizableValueException(sprintf('The data is not a valid "%s" value.', $type));
}

return $denormalized;
}

/**
* {@inheritdoc}
*/
public function supportsDenormalization($data, string $type, string $format = null)
{
if (version_compare(\PHP_VERSION, '8.1', '<')) {
return false;
}

return is_a($type, \BackedEnum::class, true);
}

/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool
{
return __CLASS__ === static::class;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?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\Fixtures\Normalizer;

class EnumBackedClassDummy
{
public EnumBackedDummy $suit;

public function __construct(EnumBackedDummy $suit = null)
{
$this->suit = $suit;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?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\Fixtures\Normalizer;

enum EnumBackedDummy: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?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\Fixtures\Normalizer;

class EnumPureClassDummy
{
public EnumPureDummy $suit;

public function __construct(EnumPureDummy $suit = null)
{
$this->suit = $suit;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?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\Fixtures\Normalizer;

enum EnumPureDummy
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

namespace Symfony\Component\Serializer\Tests\Normalizer;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer;
use Symfony\Component\Serializer\Tests\Fixtures\Normalizer\EnumBackedDummy;
use Symfony\Component\Serializer\Tests\Fixtures\Normalizer\EnumPureDummy;

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(EnumBackedDummy::Diamonds));
$this->assertFalse($this->normalizer->supportsNormalization(EnumPureDummy::Diamonds));
$this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
}

/**
* @requires PHP < 8.1
*/
public function testSupportsNormalizationEnumUnsupported()
{
$this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
}

/**
* @requires PHP >= 8.1
*/
public function testNormalize()
{
$this->assertSame('D', $this->normalizer->normalize(EnumBackedDummy::Diamonds));
}

/**
* @requires PHP >= 8.1
*/
public function testSupportsDenormalization()
{
$this->assertTrue($this->normalizer->supportsDenormalization('D', EnumBackedDummy::class));
$this->assertFalse($this->normalizer->supportsDenormalization('D', EnumPureDummy::class));
$this->assertFalse($this->normalizer->supportsDenormalization('D', \stdClass::class));
}

/**
* @requires PHP < 8.1
*/
public function testSupportsDenormalizationEnumUnsupported()
{
$this->assertFalse($this->normalizer->supportsDenormalization('D', \stdClass::class));
}

/**
* @requires PHP >= 8.1
*/
public function testDenormalize()
{
$this->assertEquals(EnumBackedDummy::Diamonds, $this->normalizer->denormalize('D', EnumBackedDummy::class));
}

/**
* @requires PHP >= 8.1
*/
public function testDenormalizeThrowsException()
{
$this->expectException(NotNormalizableValueException::class);

$this->normalizer->denormalize('Z', EnumBackedDummy::class);
}
}
27 changes: 27 additions & 0 deletions src/Symfony/Component/Serializer/Tests/SerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer;
use Symfony\Component\Serializer\Normalizer\CustomNormalizer;
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
Expand All @@ -52,6 +53,8 @@
use Symfony\Component\Serializer\Tests\Fixtures\DummyMessageNumberOne;
use Symfony\Component\Serializer\Tests\Fixtures\DummyMessageNumberTwo;
use Symfony\Component\Serializer\Tests\Fixtures\NormalizableTraversableDummy;
use Symfony\Component\Serializer\Tests\Fixtures\Normalizer\EnumBackedClassDummy;
use Symfony\Component\Serializer\Tests\Fixtures\Normalizer\EnumBackedDummy;
use Symfony\Component\Serializer\Tests\Fixtures\TraversableDummy;
use Symfony\Component\Serializer\Tests\Normalizer\TestDenormalizer;
use Symfony\Component\Serializer\Tests\Normalizer\TestNormalizer;
Expand Down Expand Up @@ -645,6 +648,30 @@ public function testDeserializeAndUnwrap()
$serializer->deserialize($jsonData, __NAMESPACE__.'\Model', 'json', [UnwrappingDenormalizer::UNWRAP_PATH => '[baz][inner]'])
);
}

/**
* @requires PHP >= 8.1
*/
public function testSerializeBackedEnum()
{
$serializer = new Serializer([new BackedEnumNormalizer(), new ObjectNormalizer()], ['json' => new JsonEncoder()]);
$card = new EnumBackedClassDummy(EnumBackedDummy::Diamonds);
$serialized = $serializer->serialize($card, 'json');

$this->assertEquals('{"suit":"D"}', $serialized);
}

/**
* @requires PHP >= 8.1
*/
public function testDeserializeBackedEnum()
{
$serialized = '{"suit": "D"}';
$serializer = new Serializer([new BackedEnumNormalizer(), new ObjectNormalizer()], ['json' => new JsonEncoder()]);
$card = $serializer->deserialize($serialized, EnumBackedClassDummy::class, 'json');

$this->assertEquals(EnumBackedDummy::Diamonds, $card->suit);
}
}

class Model
Expand Down