[Serializer] Fixed BackedEnumNormalizer priority for translatable enum#54315
Conversation
fc827ce to
b7fccc1
Compare
b7fccc1 to
56118df
Compare
b2ae966 to
42fde94
Compare
|
Good catch, thanks @IndraGunawan. |
|
What if someone relies on the current order? Do we consider this an unsupported use case? |
|
Good question. I would say yes as there are similar precedents changing e.g. compiler passes order or event listeners priority as part of a bugfix. It's probably worth being decided on a case-by-case basis and mentioned in the BC promise. |
|
This change breaks the way ApiPlatform exposes BackEnum as ApiResource |
|
As a BC break workaround, the easiest and maintainable way I found is to create a custom normalizer. For example, the project I'm working on needed the translated enumerations on serialization: use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
final readonly class AcmeNormalizer implements NormalizerInterface
{
public function __construct(private TranslatorInterface $translator)
{
}
/**
* @param TranslatableInterface $object
*/
public function normalize($object, ?string $format = null, array $context = []): string
{
return $object->trans($this->translator);
}
public function supportsNormalization($data, ?string $format = null, array $context = []): bool
{
return $data instanceof TranslatableInterface;
}
public function getSupportedTypes(?string $format): array
{
return [
TranslatableInterface::class => true,
];
}
}I don't know if this is the best way to do it or not but it seems to me to be quite maintainable. |
|
Implementation changed in #54484 |
serialize a BackedEnum that implements
TranslatableInterfacewill return the translation value instead of the enum item value. this is becauseTranslatableNormalizer(ref) has higher priority thanBackedEnumNormalizerthis PR changes the
BackedEnumNormalizerpriority higher thanTranslatableNormalizerpriority