feat: DTO\Caster\BackedEnumCaster
This commit is contained in:
@@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
namespace sammo\DTO\Caster;
|
||||||
|
use Spatie\DataTransferObject\Caster;
|
||||||
|
|
||||||
|
class BackedEnumCaster implements Caster
|
||||||
|
{
|
||||||
|
private \ReflectionMethod $backedEnumFrom;
|
||||||
|
public function __construct(
|
||||||
|
array $type,
|
||||||
|
) {
|
||||||
|
$enumType = $type[0] ?? null;
|
||||||
|
if(!is_subclass_of($enumType, \BackedEnum::class)){
|
||||||
|
throw new \Exception('Not BackedEnum: '.$enumType);
|
||||||
|
}
|
||||||
|
$reflector = new \ReflectionEnum($enumType);
|
||||||
|
$this->backedEnumFrom = $reflector->getMethod('from');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function cast(mixed $value): \BackedEnum
|
||||||
|
{
|
||||||
|
if(!is_string($value) && !is_int($value)){
|
||||||
|
throw new \Exception('BackedEnumCaster only accepts string|int');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->backedEnumFrom->invoke(null, $value);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user