MapType::describe()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Annotations\Metadata\Type;
6
7
use function assert;
8
use function is_array;
9
use function sprintf;
10
11
final class MapType implements CompositeType
12
{
13
    /** @var ScalarType|UnionType */
14
    private $keyType;
15
16
    /** @var Type */
17
    private $valueType;
18
19 8
    public function __construct(Type $keyType, Type $valueType)
20
    {
21 8
        assert($keyType instanceof ScalarType || $keyType instanceof UnionType, 'Invalid key type');
22
23 8
        $this->keyType   = $keyType;
24 8
        $this->valueType = $valueType;
25 8
    }
26
27
    public function getKeyType() : ScalarType
28
    {
29
        return $this->keyType;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->keyType could return the type Doctrine\Annotations\Metadata\Type\UnionType which is incompatible with the type-hinted return Doctrine\Annotations\Metadata\Type\ScalarType. Consider adding an additional type-check to rule them out.
Loading history...
30
    }
31
32
    public function getValueType() : Type
33
    {
34
        return $this->valueType;
35
    }
36
37 4
    public function describe() : string
38
    {
39 4
        return sprintf('array<%s, %s>', $this->keyType->describe(), $this->valueType->describe());
40
    }
41
42
    /**
43
     * @param mixed $value
44
     */
45 3
    public function validate($value) : bool
46
    {
47 3
        if (! is_array($value)) {
48
            return false;
49
        }
50
51 3
        foreach ($value as $key => $innerValue) {
52 3
            if (! $this->keyType->validate($key)) {
53 1
                return false;
54
            }
55
56 2
            if (! $this->valueType->validate($innerValue)) {
57 2
                return false;
58
            }
59
        }
60
61 2
        return true;
62
    }
63
64 1
    public function acceptsNull() : bool
65
    {
66 1
        return $this->valueType->acceptsNull();
67
    }
68
}
69