Total Complexity | 16 |
Total Lines | 71 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
12 | class UnionType implements Type |
||
13 | { |
||
14 | use Nullable, ValidatesType; |
||
15 | |||
16 | /** @var \Spatie\Typed\Type[] */ |
||
17 | private $types; |
||
18 | |||
19 | public function __construct(Type ...$types) |
||
22 | } |
||
23 | |||
24 | public function validate($value) |
||
25 | { |
||
26 | $initialValue = $this->copyValue($value); |
||
27 | |||
28 | foreach ($this->types as $type) { |
||
29 | $currentValue = $this->copyValue($initialValue); |
||
30 | |||
31 | try { |
||
32 | $currentValue = $type->validate($currentValue); |
||
33 | } catch (TypeError $typeError) { |
||
34 | continue; |
||
35 | } |
||
36 | |||
37 | if (! $this->sameType($initialValue, $currentValue, $type)) { |
||
38 | continue; |
||
39 | } |
||
40 | |||
41 | return $initialValue; |
||
42 | } |
||
43 | |||
44 | throw WrongType::withMessage("Type must be either one of: {$this->getAvailableTypesString()}"); |
||
45 | } |
||
46 | |||
47 | public function __toString(): string |
||
50 | } |
||
51 | |||
52 | private function copyValue($value) |
||
53 | { |
||
54 | if (is_object($value)) { |
||
55 | return clone $value; |
||
56 | } |
||
57 | |||
58 | return $value; |
||
59 | } |
||
60 | |||
61 | private function sameType($currentValue, $initialValue, Type $type): bool |
||
62 | { |
||
63 | if ($type instanceof NullType && $initialValue === null) { |
||
64 | return true; |
||
65 | } |
||
66 | |||
67 | if (is_scalar($initialValue) && $currentValue === $initialValue) { |
||
68 | return true; |
||
69 | } |
||
70 | |||
71 | if (is_object($initialValue) && get_class($initialValue) === get_class($currentValue)) { |
||
72 | return true; |
||
73 | } |
||
74 | |||
75 | return false; |
||
76 | } |
||
77 | |||
78 | private function getAvailableTypesString(): string |
||
83 | } |
||
84 | } |
||
85 |