Failed Conditions
Push — type ( c389f1...fc7bda )
by Michael
02:26
created

ArrayType::validate()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5.2742

Importance

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