diff --git a/src/Psl/Type/Internal/BackedEnumValueType.php b/src/Psl/Type/Internal/BackedEnumValueType.php index 83acc033..48004cce 100644 --- a/src/Psl/Type/Internal/BackedEnumValueType.php +++ b/src/Psl/Type/Internal/BackedEnumValueType.php @@ -9,8 +9,7 @@ use Psl\Type\Exception\CoercionException; use Psl\Type\Type; -use function array_map; -use function in_array; +use function is_int; use function is_string; use function Psl\Type\int; use function Psl\Type\string; @@ -46,12 +45,10 @@ public function matches(mixed $value): bool return false; } - $values = array_map( - static fn (BackedEnum $enum): string|int => $enum->value, - $this->enum::cases(), - ); - - return in_array($value, $values, true); + return match ($this->isStringBacked) { + true => is_string($value) && $this->enum::tryFrom($value) !== null, + false => is_int($value) && $this->enum::tryFrom($value) !== null, + }; } /** @@ -64,22 +61,15 @@ public function matches(mixed $value): bool */ public function coerce(mixed $value): string|int { - if ($this->isStringBacked) { - try { - $str_value = string()->coerce($value); - if ($this->matches($str_value)) { - return $str_value; - } - } catch (CoercionException) { - } - } else { - try { - $int_value = int()->coerce($value); - if ($this->matches($int_value)) { - return $int_value; - } - } catch (CoercionException) { + try { + $case = $this->isStringBacked + ? string()->coerce($value) + : int()->coerce($value); + + if ($this->matches($case)) { + return $case; } + } catch (CoercionException) { } throw CoercionException::withValue($value, $this->toString());