Test Failed
Push — master ( 2179ad...53dcee )
by Mike
02:35
created

ArrayLocator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Xervice\ArrayHandler\Business\Model\ArrayLocator;
5
6
7
class ArrayLocator implements ArrayLocatorInterface
8
{
9
    /**
10
     * @var array
11
     */
12
    private $array;
13
14
    /**
15
     * @var array
16
     */
17
    private $fieldMap;
18
19
    /**
20
     * ArrayLocator constructor.
21
     */
22 1
    public function __construct()
23
    {
24 1
        $this->array = [];
25 1
        $this->fieldMap = [];
26 1
    }
27
28
29
    /**
30
     * ArrayLocator constructor.
31
     *
32
     * @param array $array
33
     */
34
    public function init(array $array)
35
    {
36
        $this->array = $array;
37
        $this->fieldMap = [];
38
    }
39
40
    /**
41
     * @param string $path
42
     *
43
     * @return array
44
     */
45 1
    public function getKeysByPath(string $path)
46
    {
47 1
        if ($this->fieldMap === null) {
48
            $this->buildFieldMap();
49
        }
50
51 1
        return $this->getAllKeys($this->fieldMap, $path);
52
    }
53
54
    /**
55
     * @param $array
56
     * @param $path
57
     *
58
     * @return array
59
     */
60 1
    protected function getAllKeys($array, $path): array
61
    {
62 1
        $search = str_replace('\*', '.*?', preg_quote($path, '/'));
63 1
        return preg_grep('/^' . $search . '$/i', array_keys($array));
64
    }
65
66
    protected function buildFieldMap(): void
67
    {
68
        $this->fieldMap = $this->getAllFields($this->array, '', []);
69
    }
70
71
    /**
72
     * @param array $array
73
     * @param string $path
74
     * @param array $fieldMap
75
     *
76
     * @return array
77
     */
78
    protected function getAllFields(array $array, string $path, array $fieldMap): array
79
    {
80
        foreach ($array as $key => $item) {
81
            if (is_array($item)) {
82
                $fieldMap = $this->getAllFields($item, $path . '.' . $key, $fieldMap);
83
            }
84
            else {
85
                $keypath = (string) substr($path . '.' . $key, 1);
86
                $fieldMap[$keypath] = $keypath;
87
            }
88
        }
89
90
        return $fieldMap;
91
    }
92
}