1 | <?php |
||
2 | |||
3 | namespace Larapie\Actions\Concerns; |
||
4 | |||
5 | use Larapie\Actions\Attribute; |
||
6 | |||
7 | trait ResolveCasting |
||
8 | { |
||
9 | 68 | protected function resolveAttributeCasting(array $data) |
|
10 | { |
||
11 | 68 | return collect($this->rules()) |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
12 | 68 | ->filter(function ($rule) { |
|
13 | 23 | return $rule instanceof Attribute; |
|
14 | 68 | }) |
|
15 | 68 | ->intersectByKeys($data)->map(function (Attribute $attribute, $key) use ($data) { |
|
16 | 6 | return $this->processCasting($attribute, $data[$key]); |
|
17 | 68 | })->toArray(); |
|
18 | } |
||
19 | |||
20 | 6 | private function processCasting(Attribute $attribute, $value) |
|
21 | { |
||
22 | 6 | if ($attribute->isNullable() && $value === null) { |
|
23 | 1 | return $value; |
|
24 | } |
||
25 | |||
26 | 5 | if (($castFunction = $attribute->getCast()) !== null && is_callable($castFunction)) { |
|
27 | 2 | return $castFunction($value); |
|
28 | } |
||
29 | |||
30 | 5 | if ((($type = $attribute->getCast()) !== null && is_string($type)) || |
|
31 | 5 | (is_string($type = $attribute->cast(null)) && in_array(strtolower($type), ['bool', 'boolean', 'string', 'double', 'float', 'int', 'integer', 'array', 'object']))) { |
|
32 | 3 | return $this->castFromString($type, $value); |
|
33 | } |
||
34 | |||
35 | 2 | if (! ($attribute->cast(null) instanceof Attribute)) { |
|
0 ignored issues
–
show
|
|||
36 | return $attribute->cast($value); |
||
37 | } |
||
38 | |||
39 | 2 | return $value; |
|
40 | } |
||
41 | |||
42 | 3 | private function castFromString(string $type, $value) |
|
43 | { |
||
44 | 3 | switch (strtolower($type)) { |
|
45 | 3 | case 'boolean': |
|
46 | 3 | case 'bool': |
|
47 | 1 | return (bool) $value; |
|
48 | 2 | case 'string': |
|
49 | 1 | return (string) $value; |
|
50 | 1 | case 'double': |
|
51 | return (float) $value; |
||
52 | 1 | case 'integer': |
|
53 | 1 | case 'int': |
|
54 | return (int) $value; |
||
55 | 1 | case 'float': |
|
56 | return (float) $value; |
||
57 | 1 | case 'array': |
|
58 | 1 | return (array) $value; |
|
59 | case 'object': |
||
60 | return (object) $value; |
||
61 | default: |
||
62 | throw new \RuntimeException('cast type not supported'); |
||
63 | } |
||
64 | } |
||
65 | } |
||
66 |