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.
Completed
Pull Request — master (#24)
by Brent
04:03 queued 02:26
created

UnionType::sameType()   B

Complexity

Conditions 7
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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