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

Conversation

Eptagone
Copy link

@Eptagone Eptagone commented May 22, 2024

Q A
Branch? 7.2
Bug fix? yes
New feature? no
Deprecations? no
Issues
License MIT

I have an enum that implement JsonSerializable. But looks like it is not considered when serializing.

Currently, the following code doesn't work with the Serializer but it works with json_encode.

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

    public function jsonSerialize(): string {
        return 'custom_get_string';
    }
}
class MyController {
    public function __invoke(SerializerInterface $serializer) {
        dd($serializer->serialize(MyEnum::Get)); // ""GET"" , Expected result: ""custom_get_string""
    }
}

This PR allows the BackedEnumNormalizer to handle enums that implement the JsonSerializable interface.

@carsonbot
Copy link

Hey!

I see that this is your first PR. That is great! Welcome!

Symfony has a contribution guide which I suggest you to read.

In short:

  • Always add tests
  • Keep backward compatibility (see https://symfony.com/bc).
  • Bug fixes must be submitted against the lowest maintained branch where they apply (see https://symfony.com/releases)
  • Features and deprecations must be submitted against the 7.2 branch.

Review the GitHub status checks of your pull request and try to solve the reported issues. If some tests are failing, try to see if they are failing because of this change.

When two Symfony core team members approve this change, it will be merged and you will become an official Symfony contributor!
If this PR is merged in a lower version branch, it will be merged up to all maintained branches within a few days.

I am going to sit back now and wait for the reviews.

Cheers!

Carsonbot

@carsonbot

This comment was marked as outdated.

@OskarStark OskarStark changed the title [Serializer] Support enums that implement JsonSerializable in BackedEnumNormalizer [Serializer] Support enums that implement JsonSerializable in BackedEnumNormalizer May 23, 2024
@OskarStark OskarStark modified the milestones: 6.4, 7.2 May 23, 2024
@OskarStark
Copy link
Contributor

Thanks for the PR. This is a new feature and must target 7.2 branch.

@KevinVanSonsbeek
Copy link
Contributor

KevinVanSonsbeek commented May 23, 2024

I do have a question. Wouldn't it possibly be preferable to add an option to enable/disable this behavior?

As using the jsonSerialize() data automatically could (possibly?) be a breaking change. As the default serialization behavior for serializeable backed enums would change.

If you have a backed enum that implements JsonSerializable, and the jsonSerialize does not return the values the enum is backing, it would break on denormalizing. While prior to this, it would normalize and denormalize fine without any changes needed.

Edit/addition: Using the Symfony\Component\Messenger\Transport\Serialization to serialize the content of your async messenger transport could run into this problem for example.

@@ -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?

@Eptagone
Copy link
Author

Thanks for the PR. This is a new feature and must target 7.2 branch.

So. I need to close this pull request and reopen it with the change in my 7.2 branch, right?

@Eptagone
Copy link
Author

If you have a backed enum that implements JsonSerializable, and the jsonSerialize does not return the values the enum is backing, it would break on denormalizing. While prior to this, it would normalize and denormalize fine without any changes needed.

You are right @KevinVanSonsbeek! I forgot about deserialization.

@KevinVanSonsbeek
Copy link
Contributor

@Eptagone i did also just remember that symfony offers the JsonSerializableNormalizer, which can be used for any object, not just backed enums. Allthough you do need to keep in mind the normalizer ordering for it to work as expected.

<?php

declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer;
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
use Symfony\Component\Serializer\Serializer;

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

    public function jsonSerialize(): string
    {
        return 'json_serialized_get_value';
    }
}

$normalizers = [new BackedEnumNormalizer(), new JsonSerializableNormalizer()];
$serializer = new Serializer($normalizers, [new JsonEncoder()]);

dump($serializer->serialize(JsonSerializableBackedDummyEnum::Get, 'json')); // "GET"

$normalizers = [new JsonSerializableNormalizer(), new BackedEnumNormalizer()];
$serializer = new Serializer($normalizers, [new JsonEncoder()]);

dump($serializer->serialize(JsonSerializableBackedDummyEnum::Get, 'json')); // "json_serialized_get_value"

@Eptagone
Copy link
Author

@Eptagone i did also just remember that symfony offers the JsonSerializableNormalizer, which can be used for any object, not just backed enums. Allthough you do need to keep in mind the normalizer ordering for it to work as expected.

Ohh, if that exists then there is no need for this pull request. Thx
But then shouldn't JsonSerializableNormalizer have the highest priority over other normalizers?

@KevinVanSonsbeek
Copy link
Contributor

KevinVanSonsbeek commented May 27, 2024

@Eptagone i did also just remember that symfony offers the JsonSerializableNormalizer, which can be used for any object, not just backed enums. Allthough you do need to keep in mind the normalizer ordering for it to work as expected.

Ohh, if that exists then there is no need for this pull request. Thx But then shouldn't JsonSerializableNormalizer have the highest priority over other normalizers?

The serializer itself doesn't work with priority. When you go and serialize content, it checks if normalization is needed. And if normalization is needed, it will just start looping through all the normalizers it has, till it finds one that supports the input.
(default normalizer order:)
image

But in the default service definitions it does seem that the BackedEnumNormalizer is loaded with a priority of -915, while the JsonSerializableNormalizer is loaded with a priority of -950.

You could work around this problem by redefining the service for the normalizer, with a different priority though. (Allthough you'd need to keep an eye out that you don't break any other serialization logic)

# /config/services.yaml

services:
    'serializer.normalizer.backed_enum':
        class: 'Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer'
        tags:
            - { name: 'serializer.normalizer', priority: -951 } # Set to priority -951, as the JsonSerializableNormalizer is loaded at priority -950

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants