1 | <?php |
||
11 | class Caster |
||
12 | { |
||
13 | |||
14 | 10 | public static function cast($value, $type) |
|
15 | { |
||
16 | 10 | $casts = self::getCasts(); |
|
17 | 10 | $fromType = self::getValueType($value); |
|
18 | |||
19 | 10 | if (!self::shouldCast($value, $type)) { |
|
20 | 2 | return $value; |
|
21 | } |
||
22 | |||
23 | 8 | if (!self::castExists($fromType, $type)) { |
|
24 | 1 | return null; |
|
25 | } |
||
26 | |||
27 | 7 | return $casts[$type][$fromType]($value); |
|
28 | } |
||
29 | |||
30 | 10 | public static function getValueType($value) |
|
31 | { |
||
32 | 10 | $fromType = gettype($value); |
|
33 | 10 | if ($fromType == "object") { |
|
34 | 2 | $fromType = get_class($value); |
|
35 | 2 | } |
|
36 | |||
37 | 10 | return $fromType; |
|
38 | } |
||
39 | |||
40 | 10 | public static function shouldCast($value, $type) |
|
41 | { |
||
42 | 10 | $fromType = self::getValueType($value); |
|
43 | if ($fromType == $type |
||
44 | 10 | || (isset(self::getCastMap()[$type]) && $fromType == self::getCastMap()[$type]) |
|
45 | 10 | || ($type == "ExchangeFormat" && gettype($value) !== "object")) { |
|
46 | 2 | return false; |
|
47 | } |
||
48 | |||
49 | 8 | return true; |
|
50 | } |
||
51 | |||
52 | 16 | public static function castExists($from, $to) |
|
53 | { |
||
54 | 16 | $casts = self::getCasts(); |
|
55 | |||
56 | 16 | return !(empty($casts[$to][$from])); |
|
57 | } |
||
58 | |||
59 | 9 | public static function getCastMap() |
|
60 | { |
||
61 | return [ |
||
62 | 9 | 'DateTime' => 'DateTime', |
|
63 | 9 | 'dateTime' => 'DateTime', |
|
64 | 9 | 'date' => 'DateTime', |
|
65 | 'time' => 'DateTime' |
||
66 | 9 | ]; |
|
67 | } |
||
68 | |||
69 | 18 | private static function getCasts() |
|
108 | } |
||
109 |