Skip to content
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

[Serializer] Support enums that implement JsonSerializable in BackedEnumNormalizer #57068

Open
wants to merge 1 commit into
base: 6.4
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?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\Bundle\FrameworkBundle\Tests\Fixtures;

use JsonSerializable;

enum JsonSerializableBackedEnum: string implements JsonSerializable
{
case Get = 'GET';

public function jsonSerialize(): string {
return 'custom_get_string';
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Symfony\Bundle\FrameworkBundle\Tests\Functional;

use Symfony\Bundle\FrameworkBundle\Tests\Fixtures\JsonSerializableBackedEnum;
use Symfony\Bundle\FrameworkBundle\Tests\Fixtures\TranslatableBackedEnum;

/**
Expand Down Expand Up @@ -78,6 +79,15 @@ public function testSerializeTranslatableBackedEnum()

$this->assertEquals('GET', $serializer->serialize(TranslatableBackedEnum::Get, 'yaml'));
}

public function testSerializeJsonSerializableBackedEnum()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seeing how the BackedEnumNormalizer has a test itself, wouldn't it be a more fitting place to test the new behavior in the normalizers BackedEnumNormalizerTest?

{
static::bootKernel(['test_case' => 'Serializer']);

$serializer = static::getContainer()->get('serializer.alias');

$this->assertEquals('custom_get_string', $serializer->serialize(JsonSerializableBackedEnum::Get, 'yaml'));
}
}

class Foo
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down