8000 Make ConstraintValidator->formatValue aware of enums · Issue #50000 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content
Make ConstraintValidator->formatValue aware 94D8 of enums #50000
Closed
@PhoneixS

Description

@PhoneixS

Description

The Symfony\Component\Validator\ConstraintValidator->formatValue() method transforms values of a form into strings so they can be used in the error message. Now, if it is an object it checks if it's Stringable to convert it correctly, and if it isn't, it will use the value "Object".

When the value is an enum, it will consider it as an object and check if it implements Stringable, the problem is that enums can't implement the magic method __toString() so it will be always "Object" which isn't too useful.

I propose to make it enum aware by adding a check to see if it's an enum and in that case use the name as value (or a concatenation of Enum-{name} to represent it.

Example

For example, with the next code for validation of a form model:

// EnumNiceClass.php
enum EnumNiceClass: int {
    case DoSomething = 2;
    case NothingToDo = 3;
}

// FormModel.php
class FormModel {

Assert\NotIdenticalTo(
        value: EnumNiceClass::DoSomething,
)]
public EnumNiceClass $whatWillDo;

}

You will get the next message if it is invalid (with the default message This value should not be identical to {{ compared_value_type }} {{ compared_value }}.:

This value should not be identical to EnumNiceClass Object.

But changing the code to something like this:

    protected function formatValue(mixed $value, int $format = 0): string
    {

// ...

        if (\is_object($value)) {
            if (($format & self::OBJECT_TO_STRING) && $value instanceof \Stringable) {
                return $value->__toString();
            }
            
            if ($value instanceof \UnitEnum) {
                return $value->name;
            }

            return 'object';
        }
// ...

It would be:

This value should not be identical to EnumNiceClass NothingToDo.

That I think is more useful for debugging (and users in general).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0