Failed Conditions
Push — master ( 5f60a5...9b80eb )
by Rafael
21:42
created

ArrayAccessor::get()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 14
cts 14
cp 1
rs 7.7777
c 0
b 0
f 0
cc 8
eloc 15
nc 8
nop 2
crap 8
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
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 356
    public function __construct(array $data = [], $pathSeparator = ':', $includePathSeparatorInKeys = false)
70
    {
71 356
        $this->data = $data;
72 356
        $this->pathSeparator = $pathSeparator;
73 356
        $this->includePathSeparatorInKeys = $includePathSeparatorInKeys;
74 356
    }
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 57
    public function getData()
88
    {
89 57
        return $this->data;
90
    }
91
92
    /**
93
     * @param $path
94
     * @param null $defaultIfEmpty
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $defaultIfEmpty is correct as it would always require null to be passed?
Loading history...
95
     * @return array|null
96
     */
97 378
    public function get($path, $defaultIfEmpty = null)
98
    {
99 378
        $pathArray = $this->getPathAsArray($path);
100 378
        $pathSegmentCount = count($pathArray);
101
102
        switch ($pathSegmentCount) {
103
                // direct access for small paths
104 378
            case 1:
105 39
                return isset($this->data[$pathArray[0]]) ?
106 39
                    $this->data[$pathArray[0]] : $defaultIfEmpty;
107 378
            case 2:
108 75
                return isset($this->data[$pathArray[0]][$pathArray[1]]) ?
109 75
                    $this->data[$pathArray[0]][$pathArray[1]] : $defaultIfEmpty;
110 347
            case 3:
111 68
                return isset($this->data[$pathArray[0]][$pathArray[1]][$pathArray[2]]) ?
112 68
                    $this->data[$pathArray[0]][$pathArray[1]][$pathArray[2]] : $defaultIfEmpty;
113
            default:
114
                // when we have a longer path we use a loop to get the element
115 329
                $loopResult = $this->getDeepElementWithLoop($pathArray);
116 329
                return $loopResult !== null ? $loopResult : $defaultIfEmpty;
117
        }
118
    }
119
120
    /**
121
     * @param $pathArray
122
     * @return array|null
123
     */
124 329
    protected function getDeepElementWithLoop($pathArray)
125
    {
126 329
        $currentElement = $this->data;
127 329
        foreach ($pathArray as $key => $pathSegment) {
128
            // if the current path segment was not found we can stop searching
129 329
            if (!isset($currentElement[$pathSegment])) {
130 303
                break;
131
            }
132 315
            $currentElement = $currentElement[$pathSegment];
133 315
            unset($pathArray[$key]);
134
        }
135
136
        // if segments are left the item does not exist
137 329
        if (count($pathArray) > 0) {
138 303
            return null;
139
        }
140
141
        // if no items left, we've found the last element
142 231
        return $currentElement;
143
    }
144
145
    /**
146
     * @param $path
147
     * @return bool
148
     */
149 54
    public function has($path)
150
    {
151 54
        return $this->get($path) !== null;
152
    }
153
154
    /**
155
     * @param $path
156
     * @param $value
157
     */
158 70
    public function set($path, $value)
159
    {
160 70
        $pathArray = $this->getPathAsArray($path);
161 70
        $pathSegmentCount = count($pathArray);
162
163
        switch ($pathSegmentCount) {
164
            // direct access for small paths
165 70
            case 1:
166 1
               $this->data[$pathArray[0]] = $value;
167 1
               return;
168 70
            case 2:
169 66
               $this->data[$pathArray[0]][$pathArray[1]] = $value;
170 66
               return;
171
            default:
172 4
               $this->setDeepElementWithLoop($pathArray, $value);
173
        }
174 4
    }
175
176
    /**
177
     * @param $pathArray
178
     * @param mixed $value
179
     */
180 4
    protected function setDeepElementWithLoop($pathArray, $value)
181
    {
182 4
        $currentElement = &$this->data;
183 4
        foreach ($pathArray as $key => $pathSegment) {
184 4
            if (!isset($currentElement[$pathSegment])) {
185 4
                $currentElement[$pathSegment] = [];
186
            }
187
188 4
            unset($pathArray[$key]);
189
            // if segments are left the item does not exist
190 4
            if (count($pathArray) === 0) {
191 4
                $currentElement[$pathSegment] = $value;
192 4
                return;
193
            }
194
195 4
            $currentElement = &$currentElement[$pathSegment];
196
        }
197
    }
198
199
    /**
200
     * @param string $path
201
     */
202 45
    public function reset($path)
203
    {
204 45
        $pathArray = $this->getPathAsArray($path);
205 45
        $pathSegmentCount = count($pathArray);
206
207
        switch ($pathSegmentCount) {
208
            // direct access for small paths
209 45
            case 1:
210
                unset($this->data[$pathArray[0]]);
211
                 return;
212 45
            case 2:
213 41
                unset($this->data[$pathArray[0]][$pathArray[1]]);
214 41
                 return;
215
            default:
216 5
                $this->resetDeepElementWithLoop($pathArray);
217
        }
218 5
    }
219
220
    /**
221
     * @param array $pathArray
222
     */
223 5
    protected function resetDeepElementWithLoop($pathArray)
224
    {
225 5
        $currentElement = &$this->data;
226
227 5
        foreach ($pathArray as $key => $pathSegment) {
228 5
            unset($pathArray[$key]);
229
            // if segments are left the item does not exist
230 5
            if (count($pathArray) === 0) {
231 5
                unset($currentElement[$pathSegment]);
232
                // when the element is empty after unsetting the path segment, we can remove it completely
233 5
                if (empty($currentElement)) {
234 5
                    unset($currentElement);
235
                }
236
            } else {
237 5
                $currentElement = &$currentElement[$pathSegment];
238
            }
239
        }
240 5
    }
241
242
    /**
243
     * @param string $path
244
     * @return array
245
     */
246 381
    protected function getPathAsArray($path)
247
    {
248 381
        if (!$this->includePathSeparatorInKeys) {
249 81
            $pathArray = explode($this->pathSeparator, $path);
250 81
            return $pathArray;
251
        }
252
253 342
        $substitutedPath = str_replace($this->pathSeparator, $this->pathSeparator . '@@@', trim($path));
254 342
        $pathArray = array_filter(explode('@@@', $substitutedPath));
255 342
        return $pathArray;
256
    }
257
}
258