ArrayObject.php
1 month ago
AsArrayObject.php
1 month ago
AsCollection.php
1 month ago
AsEncryptedArrayObject.php
1 month ago
AsEncryptedCollection.php
1 month ago
AsEnumArrayObject.php
1 month ago
AsEnumCollection.php
1 month ago
AsStringable.php
1 month ago
Attribute.php
1 month ago
AsEnumArrayObject.php
70 lines
| 1 | <?php |
| 2 | |
| 3 | namespace IAWPSCOPED\Illuminate\Database\Eloquent\Casts; |
| 4 | |
| 5 | use BackedEnum; |
| 6 | use IAWPSCOPED\Illuminate\Contracts\Database\Eloquent\Castable; |
| 7 | use IAWPSCOPED\Illuminate\Contracts\Database\Eloquent\CastsAttributes; |
| 8 | use IAWPSCOPED\Illuminate\Support\Collection; |
| 9 | /** @internal */ |
| 10 | class AsEnumArrayObject implements Castable |
| 11 | { |
| 12 | /** |
| 13 | * Get the caster class to use when casting from / to this cast target. |
| 14 | * |
| 15 | * @template TEnum |
| 16 | * |
| 17 | * @param array{class-string<TEnum>} $arguments |
| 18 | * @return CastsAttributes<ArrayObject<array-key, TEnum>, iterable<TEnum>> |
| 19 | */ |
| 20 | public static function castUsing(array $arguments) |
| 21 | { |
| 22 | return new class($arguments) implements CastsAttributes |
| 23 | { |
| 24 | protected $arguments; |
| 25 | public function __construct(array $arguments) |
| 26 | { |
| 27 | $this->arguments = $arguments; |
| 28 | } |
| 29 | public function get($model, $key, $value, $attributes) |
| 30 | { |
| 31 | if (!isset($attributes[$key]) || \is_null($attributes[$key])) { |
| 32 | return; |
| 33 | } |
| 34 | $data = \json_decode($attributes[$key], \true); |
| 35 | if (!\is_array($data)) { |
| 36 | return; |
| 37 | } |
| 38 | $enumClass = $this->arguments[0]; |
| 39 | return new ArrayObject((new Collection($data))->map(function ($value) use($enumClass) { |
| 40 | return \is_subclass_of($enumClass, BackedEnum::class) ? $enumClass::from($value) : \constant($enumClass . '::' . $value); |
| 41 | })->toArray()); |
| 42 | } |
| 43 | public function set($model, $key, $value, $attributes) |
| 44 | { |
| 45 | if ($value === null) { |
| 46 | return [$key => null]; |
| 47 | } |
| 48 | $storable = []; |
| 49 | foreach ($value as $enum) { |
| 50 | $storable[] = $this->getStorableEnumValue($enum); |
| 51 | } |
| 52 | return [$key => \json_encode($storable)]; |
| 53 | } |
| 54 | public function serialize($model, string $key, $value, array $attributes) |
| 55 | { |
| 56 | return (new Collection($value->getArrayCopy()))->map(function ($enum) { |
| 57 | return $this->getStorableEnumValue($enum); |
| 58 | })->toArray(); |
| 59 | } |
| 60 | protected function getStorableEnumValue($enum) |
| 61 | { |
| 62 | if (\is_string($enum) || \is_int($enum)) { |
| 63 | return $enum; |
| 64 | } |
| 65 | return $enum instanceof BackedEnum ? $enum->value : $enum->name; |
| 66 | } |
| 67 | }; |
| 68 | } |
| 69 | } |
| 70 |