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

ArrayLocator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 84
Duplicated Lines 0 %

Test Coverage

Coverage 40%

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 84
ccs 10
cts 25
cp 0.4
rs 10
c 0
b 0
f 0
wmc 9

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getAllKeys() 0 4 1
A getAllFields() 0 13 3
A buildFieldMap() 0 3 1
A __construct() 0 4 1
A getKeysByPath() 0 7 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 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
}