Passed
Push — type-parser ( bda507 )
by Michael
03:05
created

MapType::acceptsNull()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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