1
|
|
|
<?php |
2
|
|
|
namespace Wandu\Caster; |
3
|
|
|
|
4
|
|
|
class Caster implements CasterInterface |
5
|
|
|
{ |
6
|
|
|
/** @var array */ |
7
|
|
|
protected static $supportCasts = [ |
8
|
|
|
'string', 'int', 'integer', 'num', 'number', 'float', 'double', 'bool', 'boolean' |
9
|
|
|
]; |
10
|
|
|
|
11
|
|
|
/** @var array */ |
12
|
|
|
protected $boolFalse = [ |
13
|
|
|
'0', 'false', 'False', 'FALSE', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' |
14
|
|
|
]; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* {@inheritdoc} |
18
|
|
|
*/ |
19
|
40 |
|
public function cast($value, $type) |
20
|
|
|
{ |
21
|
40 |
|
if (($p = strpos($type, '[]')) !== false) { |
22
|
9 |
|
$value = $this->normalizeArray($value); |
23
|
9 |
|
$type = substr($type, 0, $p); |
24
|
9 |
|
return array_map(function ($item) use ($type) { |
25
|
9 |
|
return $this->cast($item, $type); |
26
|
9 |
|
}, $value); |
27
|
|
|
} |
28
|
40 |
|
if (strpos($type, '?') !== false) { |
29
|
7 |
|
if ($value === null) { |
30
|
7 |
|
return null; |
31
|
|
|
} |
32
|
|
|
$type = str_replace($type, '?', ''); |
33
|
|
|
} |
34
|
33 |
|
return $this->castPlainType($type, $value); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param mixed $value |
39
|
|
|
* @return array |
40
|
|
|
*/ |
41
|
9 |
|
private function normalizeArray($value) |
42
|
|
|
{ |
43
|
9 |
|
if (is_array($value)) { |
44
|
3 |
|
return $value; |
45
|
|
|
} |
46
|
6 |
|
if (strpos($value, ',') !== false) { |
47
|
3 |
|
return explode(',', $value); |
48
|
|
|
} |
49
|
3 |
|
return [$value]; |
50
|
|
|
} |
51
|
|
|
|
52
|
33 |
|
private function castPlainType($type, $value) |
53
|
|
|
{ |
54
|
33 |
|
if ($value === null) { |
55
|
|
|
switch ($type) { |
56
|
7 |
|
case 'string': |
57
|
1 |
|
return ''; |
58
|
6 |
|
case 'int': |
59
|
5 |
|
case 'integer': |
60
|
1 |
|
return 0; |
61
|
5 |
|
case 'num': |
62
|
5 |
|
case 'number': |
63
|
4 |
|
case 'float': |
64
|
3 |
|
case 'double': |
65
|
3 |
|
return (float) 0; |
66
|
2 |
|
case 'bool': |
67
|
1 |
|
case 'boolean': |
68
|
2 |
|
return false; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
26 |
|
if (is_array($value)) { |
73
|
1 |
|
$value = implode(',', $value); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
switch ($type) { |
77
|
26 |
|
case 'string': |
78
|
6 |
|
return (string) $value; |
79
|
20 |
|
case 'int': |
80
|
16 |
|
case 'integer': |
81
|
7 |
|
return (int) $value; |
82
|
13 |
|
case 'num': |
83
|
13 |
|
case 'number': |
84
|
12 |
|
case 'float': |
85
|
11 |
|
case 'double': |
86
|
3 |
|
return (double) $value; |
87
|
10 |
|
case 'bool': |
88
|
9 |
|
case 'boolean': |
89
|
9 |
|
if (in_array($value, $this->boolFalse)) { |
90
|
5 |
|
return false; |
91
|
|
|
} |
92
|
4 |
|
return (bool) $value; |
93
|
|
|
} |
94
|
|
|
|
95
|
1 |
|
throw new UnsupportTypeException($type); |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|