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
02:24
created

CompoundType   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 71
rs 10
c 0
b 0
f 0
wmc 16

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 21 4
A getAvailableTypesString() 0 5 1
A copyValue() 0 7 2
A __construct() 0 3 1
A __toString() 0 3 1
B sameType() 0 15 7
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 CompoundType 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 'compound';
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