Passed
Pull Request — master (#2705)
by Rafael
34:30
created

ArrayAccessor::get()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 17
ccs 11
cts 11
cp 1
rs 9.8666
c 0
b 0
f 0
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 366
    public function __construct(array $data = [], $pathSeparator = ':', $includePathSeparatorInKeys = false)
70
    {
71 366
        $this->data = $data;
72 366
        $this->pathSeparator = $pathSeparator;
73 366
        $this->includePathSeparatorInKeys = $includePathSeparatorInKeys;
74 366
    }
75
76
    /**
77
     * @param mixed $data
78
     */
79 7
    public function setData($data)
80
    {
81 7
        $this->data = $data;
82 7
    }
83
84
    /**
85
     * @return array
86
     */
87 24
    public function getData()
88
    {
89 24
        return $this->data;
90
    }
91
92
    /**
93
     * @param $path
94
     * @param mixed $defaultIfEmpty
95
     * @return mixed
96
     */
97 365
    public function get($path, $defaultIfEmpty = null)
98
    {
99 365
        $pathArray = $this->getPathAsArray($path);
100 365
        $pathSegmentCount = count($pathArray);
101
102
        switch ($pathSegmentCount) {
103
                // direct access for small paths
104 365
            case 1:
105 1
                return $this->data[$pathArray[0]] ?? $defaultIfEmpty;
106 365
            case 2:
107 71
                return $this->data[$pathArray[0]][$pathArray[1]] ?? $defaultIfEmpty;
108 314
            case 3:
109 25
                return $this->data[$pathArray[0]][$pathArray[1]][$pathArray[2]] ?? $defaultIfEmpty;
110
            default:
111
                // when we have a longer path we use a loop to get the element
112 296
                $loopResult = $this->getDeepElementWithLoop($pathArray);
113 296
                return $loopResult ?? $defaultIfEmpty;
114
        }
115
    }
116
117
    /**
118
     * @param $pathArray
119
     * @return array|null
120
     */
121 296
    protected function getDeepElementWithLoop($pathArray)
122
    {
123 296
        $currentElement = $this->data;
124 296
        foreach ($pathArray as $key => $pathSegment) {
125
            // if the current path segment was not found we can stop searching
126 296
            if (!isset($currentElement[$pathSegment])) {
127 266
                break;
128
            }
129 281
            $currentElement = $currentElement[$pathSegment];
130 281
            unset($pathArray[$key]);
131
        }
132
133
        // if segments are left the item does not exist
134 296
        if (count($pathArray) > 0) {
135 266
            return null;
136
        }
137
138
        // if no items left, we've found the last element
139 201
        return $currentElement;
140
    }
141
142
    /**
143
     * @param $path
144
     * @return bool
145
     */
146 24
    public function has($path)
147
    {
148 24
        return $this->get($path) !== null;
149
    }
150
151
    /**
152
     * @param $path
153
     * @param $value
154
     */
155 43
    public function set($path, $value)
156
    {
157 43
        $pathArray = $this->getPathAsArray($path);
158 43
        $pathSegmentCount = count($pathArray);
159
160
        switch ($pathSegmentCount) {
161
            // direct access for small paths
162 43
            case 1:
163 1
               $this->data[$pathArray[0]] = $value;
164 1
               return;
165 43
            case 2:
166 37
               $this->data[$pathArray[0]][$pathArray[1]] = $value;
167 37
               return;
168
            default:
169 6
               $this->setDeepElementWithLoop($pathArray, $value);
170
        }
171 6
    }
172
173
    /**
174
     * @param $pathArray
175
     * @param mixed $value
176
     */
177 6
    protected function setDeepElementWithLoop($pathArray, $value)
178
    {
179 6
        $currentElement = &$this->data;
180 6
        foreach ($pathArray as $key => $pathSegment) {
181 6
            if (!isset($currentElement[$pathSegment])) {
182 6
                $currentElement[$pathSegment] = [];
183
            }
184
185 6
            unset($pathArray[$key]);
186
            // if segments are left the item does not exist
187 6
            if (count($pathArray) === 0) {
188 6
                $currentElement[$pathSegment] = $value;
189 6
                return;
190
            }
191
192 6
            $currentElement = &$currentElement[$pathSegment];
193
        }
194
    }
195
196
    /**
197
     * @param string $path
198
     */
199 17
    public function reset($path)
200
    {
201 17
        $pathArray = $this->getPathAsArray($path);
202 17
        $pathSegmentCount = count($pathArray);
203
204
        switch ($pathSegmentCount) {
205
            // direct access for small paths
206 17
            case 1:
207
                unset($this->data[$pathArray[0]]);
208
                 return;
209 17
            case 2:
210 13
                unset($this->data[$pathArray[0]][$pathArray[1]]);
211 13
                 return;
212
            default:
213 4
                $this->resetDeepElementWithLoop($pathArray);
214
        }
215 4
    }
216
217
    /**
218
     * @param array $pathArray
219
     */
220 4
    protected function resetDeepElementWithLoop($pathArray)
221
    {
222 4
        $currentElement = &$this->data;
223
224 4
        foreach ($pathArray as $key => $pathSegment) {
225 4
            unset($pathArray[$key]);
226
            // if segments are left the item does not exist
227 4
            if (count($pathArray) === 0) {
228 4
                unset($currentElement[$pathSegment]);
229
                // when the element is empty after unsetting the path segment, we can remove it completely
230 4
                if (empty($currentElement)) {
231 4
                    unset($currentElement);
232
                }
233
            } else {
234 4
                $currentElement = &$currentElement[$pathSegment];
235
            }
236
        }
237 4
    }
238
239
    /**
240
     * @param string $path
241
     * @return array
242
     */
243 368
    protected function getPathAsArray(string $path): array
244
    {
245 368
        if (!$this->includePathSeparatorInKeys) {
246 79
            $pathArray = explode($this->pathSeparator, $path);
247 79
            return $pathArray !== false ? $pathArray : [];
248
        }
249
250 306
        $substitutedPath = str_replace($this->pathSeparator, $this->pathSeparator . '@@@', trim($path));
251 306
        return array_filter(explode('@@@', $substitutedPath));
252
    }
253
}
254