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