GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

UnionType::validate()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 11
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 21
rs 9.9
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spatie\Typed\Types;
6
7
use TypeError;
8
use Spatie\Typed\Type;
9
use Spatie\Typed\ValidatesType;
10
use Spatie\Typed\Excpetions\WrongType;
11
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)
20
    {
21
        $this->types = $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
48
    {
49
        return 'union';
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
79
    {
80
        return implode(', ', array_map(function (Type $type) {
81
            return (string) $type;
82
        }, $this->types));
83
    }
84
}
85