Skip to content

Commit

Permalink
feat(type): Add value-of<BackedEnum> type
Browse files Browse the repository at this point in the history
  • Loading branch information
gsteel committed Aug 12, 2024
1 parent 323dfac commit 9a6d301
Showing 1 changed file with 13 additions and 23 deletions.
36 changes: 13 additions & 23 deletions src/Psl/Type/Internal/BackedEnumValueType.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
};
}

/**
Expand All @@ -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());
Expand Down

0 comments on commit 9a6d301

Please sign in to comment.