phpsymfony

Validate enum type with [#Assert\Choice]


I'm trying to validate enum type inside a custom DTO class. I'm trying to use the Symfony #[Assert\Choice] attribute but it seems that it doesn't work if I pass wrong value.

Custom DTO:

#[Assert\Choice(callback: 'getConditionTypes')]
public string $conditionType;

public static function getConditionTypes(): array
{
    return array_column(ConditionType::cases(), 'name');
}

Enum class:

enum ConditionType: string
{
    case NEW = "NEW";
    case USED = "USED";
    case CRASHED = "CRASHED";
    case BROKEN = "BROKEN";
    case FOR_PARTS = "FOR_PARTS";
}

When I try to pass a conditionType via Postman with a wrong value, for example "conditionType": "rand" it passes through the DTO without any issue and I'm trying to catch if there is wrong value. What am I missing?


Solution

  • Instead of providing a callback and using Assert\Choice, I used #[Assert\Type(type: ConditionType::class)] which automatically validates if the passed value is part of this enum.