Failed Conditions
Pull Request — master (#256)
by Michael
02:33
created

UnionType::validate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Annotations\Type;
6
7
use Doctrine\Annotations\Type\Exception\CompositeTypeRequiresAtLeastTwoSubTypes;
8
use function array_map;
9
use function count;
10
use function implode;
11
use function sprintf;
12
13
/**
14
 * @internal
15
 */
16
final class UnionType implements CompositeType
17
{
18
    /** @var Type[] */
19
    private $subTypes;
20
21 31
    public function __construct(Type ...$subTypes)
22
    {
23 31
        if (count($subTypes) < 2) {
24 1
            throw CompositeTypeRequiresAtLeastTwoSubTypes::fromInsufficientAmount(count($subTypes));
25
        }
26
27 31
        $this->subTypes = $subTypes;
28 31
    }
29
30
    /**
31
     * @return Type[]
32
     */
33 1
    public function getSubTypes() : array
34
    {
35 1
        return $this->subTypes;
36
    }
37
38 10
    public function describe() : string
39
    {
40 10
        return implode(
41 10
            '|',
42 10
            array_map(
43
                static function (Type $subType) : string {
44 10
                    if ($subType instanceof CompositeType) {
45 2
                        return sprintf('(%s)', $subType->describe());
46
                    }
47
48 10
                    return $subType->describe();
49 10
                },
50 10
                $this->subTypes
51
            )
52
        );
53
    }
54
55
    /**
56
     * @param mixed $value
57
     */
58 19
    public function validate($value) : bool
59
    {
60 19
        foreach ($this->subTypes as $subType) {
61 19
            if (! $subType->validate($value)) {
62 18
                continue;
63
            }
64
65 10
            return true;
66
        }
67
68 11
        return false;
69
    }
70
}
71