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