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