Twig
Twig copied to clipboard
Use value when printing BackedEnum
Let's say you have the following Enum:
enum OrderStatus: string
{
case Paid = 'paid';
}
Currently, we have to write {{ status.value }} to display an enum value.
Given that BackedEnums cannot implement Stringable / __toString, why not handle them in the EscapeRuntime?
Now we can write {{ status }} and it will print the value.
Only handled in the Escaper would lead to many frustrations/incomprehensions and a weird DX, as it won't work for filters for instance... and that would require a lot of code in many places..
Let's say you have a string my_string, a object my_stringable which class implements Stringable, and a string backed enum my_enum.
With your proposal, this would happen:
✅ {{ my_string }}
✅ {{ my_string|upper }}
✅ {{ my_stringable }}
✅ {{ my_stringable|upper }} *
✅ {{ my_enum }}
❌ {{ my_enum|upper }}
Depending on the filters, call like the last one could either display the unchanged scalar value (with filters returning the value if not stringable) or throw an error (when type is checked).. with no predictability.
But... for filter that require pre-escaped arguments, then the escaped scalar equivalent would be used.
* my_stringable|upper works because strict_types are not set so Stringable are cast to string .. which won't be possible with BackedEnum https://3v4l.org/8gl3Z#v8.3.9 VS https://3v4l.org/HsQRW#v8.3.9)
So, as long PHP scalar backed enums are not (and cannot be) Stringable in PHP ... i don't think this should be done in Twig.
Maybe a more natural way would be to implement this feature in CoreExtension::getAttribute().
@fabpot converting backed enums to their values when reading them in getAttribute would be a huge BC break and would prevent using any method of the enum (accessing their value is not the only thing you can do with an enum)
Let's close this, unless somebody has a good idea on how to solve it 😊