Passed
Push — master ( 53dcee...da1c7b )
by Mike
05:24
created

ArrayLocator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 87
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 22
dl 0
loc 87
ccs 27
cts 27
cp 1
rs 10
c 0
b 0
f 0
wmc 9

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getAllKeys() 0 4 1
A getAllFields() 0 14 3
A buildFieldMap() 0 3 1
A getKeysByPath() 0 8 2
A init() 0 4 1
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 2
    public function __construct()
23
    {
24 2
        $this->array = [];
25 2
        $this->fieldMap = null;
26 2
    }
27
28
29
    /**
30
     * ArrayLocator constructor.
31
     *
32
     * @param array $array
33
     */
34 2
    public function init(array $array)
35
    {
36 2
        $this->array = $array;
37 2
        $this->fieldMap = null;
38 2
    }
39
40
    /**
41
     * @param string $path
42
     *
43
     * @return array
44
     */
45 2
    public function getKeysByPath(string $path)
46
    {
47 2
        if ($this->fieldMap === null) {
48 2
            $this->buildFieldMap();
49
        }
50
51 2
        return array_values(
52 2
            $this->getAllKeys($this->fieldMap, $path)
53
        );
54
    }
55
56
    /**
57
     * @param $array
58
     * @param $path
59
     *
60
     * @return array
61
     */
62 2
    protected function getAllKeys($array, $path): array
63
    {
64 2
        $search = str_replace('*', '([^\.]*)', $path);
65 2
        return preg_grep('/^' . $search . '$/i', array_keys($array));
66
    }
67
68 2
    protected function buildFieldMap(): void
69
    {
70 2
        $this->fieldMap = $this->getAllFields($this->array, '', []);
71 2
    }
72
73
    /**
74
     * @param array $array
75
     * @param string $path
76
     * @param array $fieldMap
77
     *
78
     * @return array
79
     */
80 2
    protected function getAllFields(array $array, string $path, array $fieldMap): array
81
    {
82 2
        foreach ($array as $key => $item) {
83 2
            $keypath = (string) substr($path . '.' . $key, 1);
84 2
            if (is_array($item)) {
85 2
                $fieldMap[$keypath] = $keypath;
86 2
                $fieldMap = $this->getAllFields($item, $path . '.' . $key, $fieldMap);
87
            }
88
            else {
89 2
                $fieldMap[$keypath] = $keypath;
90
            }
91
        }
92
93 2
        return $fieldMap;
94
    }
95
}