diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/JsonSerializableBackedEnum.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/JsonSerializableBackedEnum.php new file mode 100644 index 000000000000..210da1dc0249 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/JsonSerializableBackedEnum.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bundle\FrameworkBundle\Tests\Fixtures; + +use JsonSerializable; + +enum JsonSerializableBackedEnum: string implements JsonSerializable +{ + case Get = 'GET'; + + public function jsonSerialize(): string { + return 'custom_get_string'; + } +} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/SerializerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/SerializerTest.php index 2856816d187a..c374f9be31ab 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/SerializerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/SerializerTest.php @@ -11,6 +11,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Functional; +use Symfony\Bundle\FrameworkBundle\Tests\Fixtures\JsonSerializableBackedEnum; use Symfony\Bundle\FrameworkBundle\Tests\Fixtures\TranslatableBackedEnum; /** @@ -78,6 +79,15 @@ public function testSerializeTranslatableBackedEnum() $this->assertEquals('GET', $serializer->serialize(TranslatableBackedEnum::Get, 'yaml')); } + + public function testSerializeJsonSerializableBackedEnum() + { + static::bootKernel(['test_case' => 'Serializer']); + + $serializer = static::getContainer()->get('serializer.alias'); + + $this->assertEquals('custom_get_string', $serializer->serialize(JsonSerializableBackedEnum::Get, 'yaml')); + } } class Foo diff --git a/src/Symfony/Component/Serializer/Normalizer/BackedEnumNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/BackedEnumNormalizer.php index 8b0aa7f5ad18..c7e559991a90 100644 --- a/src/Symfony/Component/Serializer/Normalizer/BackedEnumNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/BackedEnumNormalizer.php @@ -40,6 +40,10 @@ public function normalize(mixed $object, ?string $format = null, array $context throw new InvalidArgumentException('The data must belong to a backed enumeration.'); } + if ($object instanceof \JsonSerializable) { + return $object->jsonSerialize(); + } + return $object->value; }