Passed
Push — feature/cleanup ( d46e4b )
by Fike
02:24
created

Locator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 95%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 7
dl 0
loc 47
ccs 19
cts 20
cp 0.95
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
C locate() 0 24 7
1
<?php
2
3
namespace AmaTeam\TreeAccess;
4
5
use AmaTeam\TreeAccess\API\Exception\IllegalTargetException;
6
use AmaTeam\TreeAccess\API\Exception\MissingNodeException;
7
use AmaTeam\TreeAccess\API\NodeInterface;
8
use AmaTeam\TreeAccess\Locator\Context;
9
use AmaTeam\TreeAccess\Type\Registry;
10
11
class Locator
12
{
13
    /**
14
     * @var Registry
15
     */
16
    private $registry;
17
18 18
    public function __construct(Registry $registry)
19
    {
20 18
        $this->registry = $registry;
21 18
    }
22
23
    /**
24
     * @param NodeInterface $root
25
     * @param array $path
26
     * @param Context $context
27
     *
28
     * @return NodeInterface|null
29
     *
30
     * @throws MissingNodeException
31
     * @throws IllegalTargetException
32
     */
33 17
    public function locate(NodeInterface $root, array $path, Context $context)
34
    {
35 17
        $currentPath = [];
36 17
        $cursor = $root;
37 17
        foreach ($path as $segment) {
38 14
            $currentPath[] = $segment;
39 14
            $value = &$cursor->getValue();
40 14
            $accessor = $this->registry->getAccessor(gettype($value));
41 14
            if (!$accessor) {
42 1
                if ($context->shouldIgnoreIllegal()) {
43
                    return null;
44
                }
45 1
                throw new IllegalTargetException($currentPath);
46
            }
47 13
            if (!$accessor || !$accessor->exists($value, $segment)) {
48 3
                if ($context->shouldIgnoreMissing()) {
49 2
                    return null;
50
                }
51 1
                throw new MissingNodeException($currentPath);
52
            }
53 10
            $cursor = $accessor->read($value, $segment);
54
        }
55 13
        return Node::withPath($cursor, $path);
56
    }
57
}
58