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

UnionType   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
eloc 18
dl 0
loc 53
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubTypes() 0 3 1
A validate() 0 11 3
A describe() 0 13 2
A __construct() 0 7 2
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