Passed
Push — master ( 3e6704...db24af )
by Rafael
43:26 queued 10s
created

ArrayAccessor::get()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
dl 0
loc 17
ccs 12
cts 12
cp 1
rs 9.8666
cc 4
nc 4
nop 2
crap 4
1
<?php
2
namespace ApacheSolrForTypo3\Solr\System\Util;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2010-2016 Timo Schmidt <[email protected]
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 3 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
/**
28
 * Class ArrayAccessor
29
 *
30
 * LowLevel class to access nested associative arrays with
31
 * a path.
32
 *
33
 * Example:
34
 *
35
 * $data = [];
36
 * $data['foo']['bar'] = 'bla';
37
 *
38
 * $accessor = new ArrayAccesor($data);
39
 * $value = $accessor->get('foo.bar');
40
 *
41
 * echo $value;
42
 *
43
 * the example above will output "bla"
44
 *
45
 */
46
class ArrayAccessor
47
{
48
49
    /**
50
     * @var array
51
     */
52
    protected $data;
53
54
    /**
55
     * @var string
56
     */
57
    protected $pathSeparator = ':';
58
59
    /**
60
     * @var bool
61
     */
62
    protected $includePathSeparatorInKeys = false;
63
64
    /**
65
     * @param array $data
66
     * @param string $pathSeparator
67
     * @param bool $includePathSeparatorInKeys
68
     */
69 201
    public function __construct(array $data = [], $pathSeparator = ':', $includePathSeparatorInKeys = false)
70
    {
71 201
        $this->data = $data;
72 201
        $this->pathSeparator = $pathSeparator;
73 201
        $this->includePathSeparatorInKeys = $includePathSeparatorInKeys;
74 201
    }
75
76
    /**
77
     * @param mixed $data
78
     */
79 21
    public function setData($data)
80
    {
81 21
        $this->data = $data;
82 21
    }
83
84
    /**
85
     * @return array
86
     */
87 43
    public function getData()
88
    {
89 43
        return $this->data;
90
    }
91
92
    /**
93
     * @param $path
94
     * @param mixed $defaultIfEmpty
95
     * @return mixed
96
     */
97 167
    public function get($path, $defaultIfEmpty = null)
98
    {
99 167
        $pathArray = $this->getPathAsArray($path);
100 167
        $pathSegmentCount = count($pathArray);
101
102
        switch ($pathSegmentCount) {
103
                // direct access for small paths
104 167
            case 1:
105 36
                return $this->data[$pathArray[0]] ?? $defaultIfEmpty;
106 36
            case 2:
107 167
                return $this->data[$pathArray[0]][$pathArray[1]] ?? $defaultIfEmpty;
108 43
            case 3:
109 43
                return $this->data[$pathArray[0]][$pathArray[1]][$pathArray[2]] ?? $defaultIfEmpty;
110 167
            default:
111 49
                // when we have a longer path we use a loop to get the element
112 49
                $loopResult = $this->getDeepElementWithLoop($pathArray);
113
                return $loopResult ?? $defaultIfEmpty;
114
        }
115 167
    }
116 167
117
    /**
118
     * @param $pathArray
119
     * @return array|null
120
     */
121
    protected function getDeepElementWithLoop($pathArray)
122
    {
123
        $currentElement = $this->data;
124 167
        foreach ($pathArray as $key => $pathSegment) {
125
            // if the current path segment was not found we can stop searching
126 167
            if (!isset($currentElement[$pathSegment])) {
127 167
                break;
128
            }
129 167
            $currentElement = $currentElement[$pathSegment];
130 163
            unset($pathArray[$key]);
131
        }
132 167
133 167
        // if segments are left the item does not exist
134
        if (count($pathArray) > 0) {
135
            return null;
136
        }
137 167
138 163
        // if no items left, we've found the last element
139
        return $currentElement;
140
    }
141
142 147
    /**
143
     * @param $path
144
     * @return bool
145
     */
146
    public function has($path)
147
    {
148
        return $this->get($path) !== null;
149 41
    }
150
151 41
    /**
152
     * @param $path
153
     * @param $value
154
     */
155
    public function set($path, $value)
156
    {
157
        $pathArray = $this->getPathAsArray($path);
158 44
        $pathSegmentCount = count($pathArray);
159
160 44
        switch ($pathSegmentCount) {
161 44
            // direct access for small paths
162
            case 1:
163
               $this->data[$pathArray[0]] = $value;
164
               return;
165 44
            case 2:
166
               $this->data[$pathArray[0]][$pathArray[1]] = $value;
167
               return;
168 44
            default:
169 44
               $this->setDeepElementWithLoop($pathArray, $value);
170 44
        }
171
    }
172
173
    /**
174
     * @param $pathArray
175
     * @param mixed $value
176
     */
177
    protected function setDeepElementWithLoop($pathArray, $value)
178
    {
179
        $currentElement = &$this->data;
180
        foreach ($pathArray as $key => $pathSegment) {
181
            if (!isset($currentElement[$pathSegment])) {
182
                $currentElement[$pathSegment] = [];
183
            }
184
185
            unset($pathArray[$key]);
186
            // if segments are left the item does not exist
187
            if (count($pathArray) === 0) {
188
                $currentElement[$pathSegment] = $value;
189
                return;
190
            }
191
192
            $currentElement = &$currentElement[$pathSegment];
193
        }
194
    }
195
196
    /**
197
     * @param string $path
198
     */
199
    public function reset($path)
200
    {
201
        $pathArray = $this->getPathAsArray($path);
202 33
        $pathSegmentCount = count($pathArray);
203
204 33
        switch ($pathSegmentCount) {
205 33
            // direct access for small paths
206
            case 1:
207
                unset($this->data[$pathArray[0]]);
208
                 return;
209 33
            case 2:
210
                unset($this->data[$pathArray[0]][$pathArray[1]]);
211
                 return;
212 33
            default:
213 33
                $this->resetDeepElementWithLoop($pathArray);
214 33
        }
215
    }
216 1
217
    /**
218 1
     * @param array $pathArray
219
     */
220
    protected function resetDeepElementWithLoop($pathArray)
221
    {
222
        $currentElement = &$this->data;
223 1
224
        foreach ($pathArray as $key => $pathSegment) {
225 1
            unset($pathArray[$key]);
226
            // if segments are left the item does not exist
227 1
            if (count($pathArray) === 0) {
228 1
                unset($currentElement[$pathSegment]);
229
                // when the element is empty after unsetting the path segment, we can remove it completely
230 1
                if (empty($currentElement)) {
231 1
                    unset($currentElement);
232
                }
233 1
            } else {
234 1
                $currentElement = &$currentElement[$pathSegment];
235
            }
236
        }
237 1
    }
238
239
    /**
240 1
     * @param string $path
241
     * @return array
242
     */
243
    protected function getPathAsArray(string $path): array
244
    {
245
        if (!$this->includePathSeparatorInKeys) {
246 167
            $pathArray = explode($this->pathSeparator, $path);
247
            return $pathArray !== false ? $pathArray : [];
248 167
        }
249 44
250 44
        $substitutedPath = str_replace($this->pathSeparator, $this->pathSeparator . '@@@', trim($path));
251
        return array_filter(explode('@@@', $substitutedPath));
252
    }
253
}
254