ArrayAccessor::enumerate()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 8
ccs 6
cts 6
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace AmaTeam\TreeAccess\Type;
4
5
use AmaTeam\TreeAccess\API\Exception\MissingNodeException;
6
use AmaTeam\TreeAccess\API\Exception\RuntimeException;
7
use AmaTeam\TreeAccess\API\TypeAccessorInterface;
8
use AmaTeam\TreeAccess\Node;
9
10
class ArrayAccessor implements TypeAccessorInterface
11
{
12
    /**
13
     * @inheritDoc
14
     */
15 8
    public function read(&$item, $key)
16
    {
17 8
        $this->assertExists($item, $key);
18 7
        return new Node([$key], $item[$key]);
19
    }
20
21
    /**
22
     * @inheritDoc
23
     */
24 4
    public function write(&$item, $key, $value)
25
    {
26 4
        $this->assertArray($item);
27 4
        $item[$key] = $value;
28 4
        return new Node([$key], $value);
29
    }
30
31
    /**
32
     * @inheritDoc
33
     */
34 13
    public function exists($item, $key)
35
    {
36 13
        $this->assertArray($item);
37 12
        return array_key_exists($key, $item);
38
    }
39
40
    /**
41
     * @inheritDoc
42
     */
43 2
    public function enumerate($item)
44
    {
45 2
        $this->assertArray($item);
46 2
        $target = [];
47 2
        foreach ($item as $key => &$value) {
48 1
            $target[$key] = new Node([$key], $value);
49
        }
50 2
        return $target;
51
    }
52
53
    /**
54
     * @param array $item
55
     * @param string $key
56
     */
57 8
    private function assertExists($item, $key)
58
    {
59 8
        if (!$this->exists($item, $key)) {
60 1
            $template = 'Key `%s` doesn\'t exist in passed array';
61 1
            $message = sprintf($template, $key);
62 1
            throw new MissingNodeException([$key], $message);
63
        }
64 7
    }
65
66
    /**
67
     * @param array $item
68
     */
69 17
    private function assertArray($item)
70
    {
71 17
        if (!is_array($item)) {
72 1
            throw new RuntimeException('Non-array item passed');
73
        }
74 16
    }
75
}
76