|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Hypervel\Foundation\Http\Casts; |
| 6 | + |
| 7 | +use ArrayObject; |
| 8 | +use BackedEnum; |
| 9 | +use Hypervel\Foundation\Http\Contracts\Castable; |
| 10 | +use Hypervel\Foundation\Http\Contracts\CastInputs; |
| 11 | +use Hypervel\Support\Collection; |
| 12 | + |
| 13 | +use function Hypervel\Support\enum_value; |
| 14 | + |
| 15 | +class AsEnumArrayObject implements Castable |
| 16 | +{ |
| 17 | + /** |
| 18 | + * Get the caster class to use when casting from / to this cast target. |
| 19 | + * |
| 20 | + * @param string $class The enum class name |
| 21 | + */ |
| 22 | + public static function of(string $class): string |
| 23 | + { |
| 24 | + return static::class . ':' . $class; |
| 25 | + } |
| 26 | + |
| 27 | + /** |
| 28 | + * Get the caster class to use when casting from / to this cast target. |
| 29 | + */ |
| 30 | + public static function castUsing(array $arguments = []): CastInputs |
| 31 | + { |
| 32 | + return new class($arguments) implements CastInputs { |
| 33 | + public function __construct(protected array $arguments) |
| 34 | + { |
| 35 | + } |
| 36 | + |
| 37 | + public function get(string $key, mixed $value, array $inputs): mixed |
| 38 | + { |
| 39 | + if (! isset($inputs[$key]) || ! is_array($value)) { |
| 40 | + return null; |
| 41 | + } |
| 42 | + |
| 43 | + $enumClass = $this->arguments[0]; |
| 44 | + |
| 45 | + return new ArrayObject( |
| 46 | + (new Collection($value))->map(function ($item) use ($enumClass) { |
| 47 | + if ($item instanceof $enumClass) { |
| 48 | + return $item; |
| 49 | + } |
| 50 | + |
| 51 | + return is_subclass_of($enumClass, BackedEnum::class) |
| 52 | + ? $enumClass::from($item) |
| 53 | + : constant($enumClass . '::' . $item); |
| 54 | + })->toArray() |
| 55 | + ); |
| 56 | + } |
| 57 | + |
| 58 | + public function set(string $key, mixed $value, array $inputs): array |
| 59 | + { |
| 60 | + if ($value === null) { |
| 61 | + return [$key => null]; |
| 62 | + } |
| 63 | + |
| 64 | + $storable = []; |
| 65 | + |
| 66 | + foreach ($value as $enum) { |
| 67 | + $storable[] = $this->getStorableEnumValue($enum); |
| 68 | + } |
| 69 | + |
| 70 | + return [$key => $storable]; |
| 71 | + } |
| 72 | + |
| 73 | + protected function getStorableEnumValue(mixed $enum): mixed |
| 74 | + { |
| 75 | + if (is_string($enum) || is_int($enum)) { |
| 76 | + return $enum; |
| 77 | + } |
| 78 | + |
| 79 | + return enum_value($enum); |
| 80 | + } |
| 81 | + }; |
| 82 | + } |
| 83 | +} |
0 commit comments