symfony / symfony

The Symfony PHP framework
https://symfony.com
MIT License
29.6k stars 9.42k forks source link

[Config] Support passing the value of backed enums in enumNode #57659

Open Seldaek opened 2 months ago

Seldaek commented 2 months ago

Description

This idea came up while looking at this mess. I figured it would be nice if you could just pass ->enumNode(BackedEnum::cases()) or even ->enumNode(BackedEnum::class). Turns out it is possible (the former) thanks to https://github.com/symfony/symfony/pull/49098 but then if you do that the users have to also manage to create enum cases like foo: !php/enum \App\Enum\FooEnum::Bar, which requires a lot of internal knowledge and is not super user friendly.

So my request is.. Could we make it so that if all enumNode cases are actual enum instances and there is no plain string in there, and the enum is backed, then if a string is passed in as value in the config it would do enum::tryFrom(string) to convert it automatically?

Example

foo: "bar" would auto-convert to \App\Enum\FooEnum::Bar

janmartenjongerius commented 2 months ago

The only downside I could see, which is a faux pas anyway, is when someone changes the value of an enum case, to correct it, while keeping the case in-tact.

However, that's a risk one has to accept when configuring without explicitly using the enum case in the first place. Also, this same risk is present on non-enum configuration. At the very least, an enum already denotes the maintainer is more careful about selecting allowed values for configuration.

The risk could even be mitigated by the maintainer through overriding the tryFrom initializer and supporting the previously accepted value for the corrected case.

:+1: I'm really stoked for this enhancement.

alexandre-daubois commented 1 month ago

I really like this feature! I gave a try on the implementation, tell me what you think :slightly_smiling_face: