EnumMapper
Maps an input value (a backing scalar or null) to the corresponding case of a PHP backed enum.
Accepts the following input types:
- A scalar matching a case's backing value (
stringorint). - An instance of the enum itself.
null— left asnull, subject to validation.
Non-null values are coerced to the matching enum case before validation. A scalar that does not map to any case throws BindMismatchException (not a validation error).
Validation possibilities
| Parameter | Type | Default | Description |
|---|---|---|---|
| $enum | ReflectionEnum|string | — | The target backed enum (class name or reflection). |
| $mandatory | bool | false | Rejects null input. |
Example: mapping to an enum case
enum MockEnum: string {
case EUROPE_ZURICH = 'Europe/Zurich';
}
$result = Bind::values('Europe/Zurich', null)->map(Mappers::enum(MockEnum::class))->toArray()->exec();
var_dump($result->get());
Output:
array(2) {
[0]=>
enum(MockEnum::EUROPE_ZURICH)
[1]=>
NULL
}
Example: mandatory
$result = Bind::attrs(['timezone' => null])
->props(['timezone'], Mappers::enum(MockEnum::class, true))
->toArray()
->exec();
var_dump($result->isValid()); // false
var_dump($result->getErrorMap()->getChild('timezone')->isEmpty()); // false because mandatory
A non-matching scalar such as 'unknown/unknown' throws BindMismatchException rather than recording a validation error.