Total Complexity | 12 |
Total Lines | 51 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
10 | trait Castable |
||
11 | { |
||
12 | 152 | protected function cast(array &$source) |
|
13 | { |
||
14 | 152 | foreach ($source as $key => &$value) { |
|
15 | 150 | $value = $this->castValue($key, $value); |
|
16 | } |
||
17 | 152 | } |
|
18 | |||
19 | 174 | protected function castValue(string $key, $value) |
|
20 | { |
||
21 | 174 | $cast = $this->castKey($key); |
|
22 | |||
23 | 174 | $method = $this->castMethodName($cast); |
|
24 | |||
25 | 174 | return $this->{$method}($value); |
|
26 | } |
||
27 | |||
28 | 174 | protected function castKey(string $key): string |
|
29 | { |
||
30 | 174 | return $this->casts[$key] ?? 'string'; |
|
31 | } |
||
32 | |||
33 | 174 | protected function castMethodName(string $key): string |
|
34 | { |
||
35 | 174 | return (string) Str::of($key)->start('castTo_')->camel(); |
|
36 | } |
||
37 | |||
38 | 70 | protected function castToArray($value): array |
|
39 | { |
||
40 | 70 | if (empty($value)) { |
|
41 | 10 | return []; |
|
42 | } |
||
43 | |||
44 | 62 | if (is_array($value)) { |
|
45 | 16 | return $value; |
|
46 | } |
||
47 | |||
48 | 53 | parse_str($value, $output); |
|
49 | |||
50 | 53 | return $output; |
|
51 | } |
||
52 | |||
53 | 55 | protected function castToInteger($value): ?int |
|
54 | { |
||
55 | 55 | return empty($value) && ! is_numeric($value) ? null : $value; |
|
56 | } |
||
57 | |||
58 | 166 | protected function castToString(?string $value): string |
|
61 | } |
||
62 | } |
||
63 |