Failed Conditions
Push — master ( ecccd5...ae55c7 )
by Marco
33s
created

ArrayType::describe()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 4
nc 2
nop 0
crap 4
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 296
    public function __construct(Type $keyType, Type $valueType)
22
    {
23 296
        $this->keyType   = $keyType;
24 296
        $this->valueType = $valueType;
25 296
    }
26
27 1
    public function getKeyType() : Type
28
    {
29 1
        return $this->keyType;
30
    }
31
32 205
    public function getValueType() : Type
33
    {
34 205
        return $this->valueType;
35
    }
36
37 7
    public function describe() : string
38
    {
39 7
        if ($this->keyType instanceof MixedType
40 5
            || $this->keyType->describe() === 'int|string'
41 7
            || $this->keyType->describe() === 'string|int'
42
        ) {
43 4
            return sprintf('array<%s>', $this->valueType->describe());
44
        }
45
46 3
        return sprintf('array<%s, %s>', $this->keyType->describe(), $this->valueType->describe());
47
    }
48
49
    /**
50
     * @param mixed $value
51
     */
52 218
    public function validate($value) : bool
53
    {
54 218
        if (! is_array($value)) {
55 3
            return false;
56
        }
57
58 215
        foreach ($value as $key => $innerValue) {
59 213
            if (! $this->keyType->validate($key)) {
60 1
                return false;
61
            }
62
63 212
            if (! $this->valueType->validate($innerValue)) {
64 39
                return false;
65
            }
66
        }
67
68 211
        return true;
69
    }
70
}
71