Skip to main content

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 (string or int).
  • An instance of the enum itself.
  • null — left as null, 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​

ParameterTypeDefaultDescription
$enumReflectionEnum|string—The target backed enum (class name or reflection).
$mandatoryboolfalseRejects 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.