Passed
Pull Request — master (#115)
by Sergei
02:58
created

ArrayHelper   F

Complexity

Total Complexity 147

Size/Duplication

Total Lines 1260
Duplicated Lines 0 %

Test Coverage

Coverage 99.65%

Importance

Changes 13
Bugs 1 Features 0
Metric Value
wmc 147
eloc 265
c 13
b 1
f 0
dl 0
loc 1260
ccs 286
cts 287
cp 0.9965
rs 2

28 Methods

Rating   Name   Duplication   Size   Complexity  
A removeByPath() 0 3 1
C toArray() 0 55 15
B merge() 0 25 10
A setValue() 0 23 6
A setValueByPath() 0 3 2
C filter() 0 55 13
A getExistsKeys() 0 11 2
B isAssociative() 0 23 7
A pathExists() 0 7 1
A isIn() 0 14 6
A getObjectVars() 0 3 1
A getValueByPath() 0 10 2
A isIndexed() 0 18 5
B index() 0 41 9
B htmlDecode() 0 25 7
A group() 0 3 1
A remove() 0 21 6
A keyExists() 0 19 6
A getColumn() 0 16 4
A rootKeyExists() 0 15 4
B htmlEncode() 0 25 7
B map() 0 26 7
A getValue() 0 20 6
A removeValue() 0 13 3
A normalizeArrayKey() 0 3 2
A isSubset() 0 10 3
A getRootValue() 0 23 5
A parseMixedPath() 0 24 6

How to fix   Complexity   

Complex Class

Complex classes like ArrayHelper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ArrayHelper, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Arrays;
6
7
use Closure;
8
use InvalidArgumentException;
9
use Throwable;
10
use Yiisoft\Strings\NumericHelper;
11
use Yiisoft\Strings\StringHelper;
12
13
use function array_key_exists;
14
use function count;
15
use function gettype;
16
use function in_array;
17
use function is_array;
18
use function is_float;
19
use function is_int;
20
use function is_object;
21
use function is_string;
22
23
/**
24
 * Yii array helper provides static methods allowing you to deal with arrays more efficiently.
25
 *
26
 * @psalm-type ArrayKey = float|int|string|array<array-key,float|int|string>
27
 * @psalm-type ArrayPath = float|int|string|array<array-key,float|int|string|array<array-key,float|int|string>>
28
 */
29
final class ArrayHelper
30
{
31
    /**
32
     * Converts an object or an array of objects into an array.
33
     *
34
     * For example:
35
     *
36
     * ```php
37
     * [
38
     *     Post::class => [
39
     *         'id',
40
     *         'title',
41
     *         'createTime' => 'created_at',
42
     *         'length' => function ($post) {
43
     *             return strlen($post->content);
44
     *         },
45
     *     ],
46
     * ]
47
     * ```
48
     *
49
     * The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
50
     *
51
     * ```php
52
     * [
53
     *     'id' => 123,
54
     *     'title' => 'test',
55
     *     'createTime' => '2013-01-01 12:00AM',
56
     *     'length' => 301,
57
     * ]
58
     * ```
59
     *
60
     * @param array|object|string $object The object to be converted into an array.
61
     *
62
     * It is possible to provide default way of converting object to array for a specific class by implementing
63
     * {@see \Yiisoft\Arrays\ArrayableInterface} in its class.
64
     * @param array $properties A mapping from object class names to the properties that need to put into
65
     * the resulting arrays. The properties specified for each class is an array of the following format:
66
     *
67
     * - A field name to include as is.
68
     * - A key-value pair of desired array key name and model column name to take value from.
69
     * - A key-value pair of desired array key name and a callback which returns value.
70
     * @param bool $recursive Whether to recursively converts properties which are objects into arrays.
71
     *
72
     * @return array The array representation of the object.
73
     */
74 6
    public static function toArray($object, array $properties = [], bool $recursive = true): array
75
    {
76 6
        if (is_array($object)) {
77 5
            if ($recursive) {
78
                /** @var mixed $value */
79 4
                foreach ($object as $key => $value) {
80 4
                    if (is_array($value) || is_object($value)) {
81 4
                        $object[$key] = self::toArray($value, $properties);
82
                    }
83
                }
84
            }
85
86 5
            return $object;
87
        }
88
89 4
        if (is_object($object)) {
90 4
            if (!empty($properties)) {
91 1
                $className = $object::class;
92 1
                if (!empty($properties[$className])) {
93 1
                    $result = [];
94
                    /**
95
                     * @var int|string $key
96
                     * @var string $name
97
                     */
98 1
                    foreach ($properties[$className] as $key => $name) {
99 1
                        if (is_int($key)) {
100
                            /** @var mixed */
101 1
                            $result[$name] = $object->$name;
102
                        } else {
103
                            /** @var mixed */
104 1
                            $result[$key] = self::getValue($object, $name);
105
                        }
106
                    }
107
108 1
                    return $recursive ? self::toArray($result, $properties) : $result;
109
                }
110
            }
111 4
            if ($object instanceof ArrayableInterface) {
112 3
                $result = $object->toArray([], [], $recursive);
113
            } else {
114 4
                $result = [];
115
                /**
116
                 * @var string $key
117
                 * @var mixed $value
118
                 */
119 4
                foreach ($object as $key => $value) {
120
                    /** @var mixed */
121 4
                    $result[$key] = $value;
122
                }
123
            }
124
125 4
            return $recursive ? self::toArray($result, $properties) : $result;
126
        }
127
128 1
        return [$object];
129
    }
130
131
    /**
132
     * Merges two or more arrays into one recursively.
133
     * If each array has an element with the same string key value, the latter
134
     * will overwrite the former (different from {@see array_merge_recursive()}).
135
     * Recursive merging will be conducted if both arrays have an element of array
136
     * type and are having the same key.
137
     * For integer-keyed elements, the elements from the latter array will
138
     * be appended to the former array.
139
     *
140
     * @param array ...$arrays Arrays to be merged.
141
     *
142
     * @return array The merged array (the original arrays are not changed).
143
     */
144 4
    public static function merge(...$arrays): array
145
    {
146 4
        $result = array_shift($arrays) ?: [];
147 4
        while (!empty($arrays)) {
148
            /** @var mixed $value */
149 3
            foreach (array_shift($arrays) as $key => $value) {
150 3
                if (is_int($key)) {
151 3
                    if (array_key_exists($key, $result)) {
152 3
                        if ($result[$key] !== $value) {
153
                            /** @var mixed */
154 3
                            $result[] = $value;
155
                        }
156
                    } else {
157
                        /** @var mixed */
158 3
                        $result[$key] = $value;
159
                    }
160 1
                } elseif (isset($result[$key]) && is_array($value) && is_array($result[$key])) {
161 1
                    $result[$key] = self::merge($result[$key], $value);
162
                } else {
163
                    /** @var mixed */
164 1
                    $result[$key] = $value;
165
                }
166
            }
167
        }
168 4
        return $result;
169
    }
170
171
    /**
172
     * Retrieves the value of an array element or object property with the given key or property name.
173
     * If the key does not exist in the array or object, the default value will be returned instead.
174
     *
175
     * Below are some usage examples,
176
     *
177
     * ```php
178
     * // Working with array:
179
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($_POST, 'username');
180
     *
181
     * // Working with object:
182
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($user, 'username');
183
     *
184
     * // Working with anonymous function:
185
     * $fullName = \Yiisoft\Arrays\ArrayHelper::getValue($user, function ($user, $defaultValue) {
186
     *     return $user->firstName . ' ' . $user->lastName;
187
     * });
188
     *
189
     * // Using an array of keys to retrieve the value:
190
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
191
     * ```
192
     *
193
     * @param array|object $array Array or object to extract value from.
194
     * @param array|Closure|float|int|string $key Key name of the array element,
195
     * an array of keys or property name of the object, or an anonymous function
196
     * returning the value. The anonymous function signature should be:
197
     * `function($array, $defaultValue)`.
198
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
199
     * getting value from an object.
200
     *
201
     * @psalm-param ArrayKey|Closure $key
202
     *
203
     * @return mixed The value of the element if found, default value otherwise.
204
     */
205 94
    public static function getValue(array|object $array, array|Closure|float|int|string $key, mixed $default = null)
206
    {
207 94
        if ($key instanceof Closure) {
0 ignored issues
show
introduced by
$key is never a sub-type of Closure.
Loading history...
208 16
            return $key($array, $default);
209
        }
210
211 86
        if (is_array($key)) {
0 ignored issues
show
introduced by
The condition is_array($key) is always true.
Loading history...
212
            /** @psalm-var array<mixed,string|int> $key */
213 42
            $lastKey = array_pop($key);
214 42
            foreach ($key as $keyPart) {
215
                /** @var mixed */
216 39
                $array = self::getRootValue($array, $keyPart, null);
217 39
                if (!is_array($array) && !is_object($array)) {
218 10
                    return $default;
219
                }
220
            }
221 33
            return self::getRootValue($array, $lastKey, $default);
222
        }
223
224 46
        return self::getRootValue($array, $key, $default);
225
    }
226
227
    /**
228
     * @param mixed $array Array or object to extract value from, otherwise method will return $default.
229
     * @param float|int|string $key Key name of the array element or property name of the object.
230
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
231
     * getting value from an object.
232
     *
233
     * @return mixed The value of the element if found, default value otherwise.
234
     */
235 113
    private static function getRootValue(mixed $array, float|int|string $key, mixed $default): mixed
236
    {
237 113
        if (is_array($array)) {
238 101
            $key = self::normalizeArrayKey($key);
239 101
            return array_key_exists($key, $array) ? $array[$key] : $default;
240
        }
241
242 14
        if (is_object($array)) {
243
            try {
244
                /** @psalm-suppress MixedPropertyFetch */
245 14
                return $array::$$key;
246 14
            } catch (Throwable) {
0 ignored issues
show
Unused Code introduced by
catch (\Throwable) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
247
                /**
248
                 * This is expected to fail if the property does not exist, or __get() is not implemented.
249
                 * It is not reliably possible to check whether a property is accessible beforehand.
250
                 *
251
                 * @psalm-suppress MixedPropertyFetch
252
                 */
253 14
                return $array->$key;
254
            }
255
        }
256
257
        return $default;
258
    }
259
260
    /**
261
     * Retrieves the value of an array element or object property with the given key or property name.
262
     * If the key does not exist in the array or object, the default value will be returned instead.
263
     *
264
     * The key may be specified in a dot-separated format to retrieve the value of a sub-array or the property
265
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
266
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
267
     * or `$array->x` is neither an array nor an object, the default value will be returned.
268
     * Note that if the array already has an element `x.y.z`, then its value will be returned
269
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
270
     * like `['x', 'y', 'z']`.
271
     *
272
     * Below are some usage examples,
273
     *
274
     * ```php
275
     * // Using separated format to retrieve the property of embedded object:
276
     * $street = \Yiisoft\Arrays\ArrayHelper::getValue($users, 'address.street');
277
     *
278
     * // Using an array of keys to retrieve the value:
279
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
280
     * ```
281
     *
282
     * @param array|object $array Array or object to extract value from.
283
     * @param array|Closure|float|int|string $path Key name of the array element, an array of keys or property name
284
     * of the object, or an anonymous function returning the value. The anonymous function signature should be:
285
     * `function($array, $defaultValue)`.
286
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
287
     * getting value from an object.
288
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
289
     * to "." (dot).
290
     *
291
     * @psalm-param ArrayPath|Closure $path
292
     *
293
     * @return mixed The value of the element if found, default value otherwise.
294
     */
295 37
    public static function getValueByPath(
296
        array|object $array,
297
        array|Closure|float|int|string $path,
298
        mixed $default = null,
299
        string $delimiter = '.'
300
    ) {
301 37
        return self::getValue(
302 37
            $array,
303 37
            $path instanceof Closure ? $path : self::parseMixedPath($path, $delimiter),
0 ignored issues
show
introduced by
$path is never a sub-type of Closure.
Loading history...
304 37
            $default
305 37
        );
306
    }
307
308
    /**
309
     * Writes a value into an associative array at the key path specified.
310
     * If there is no such key path yet, it will be created recursively.
311
     * If the key exists, it will be overwritten.
312
     *
313
     * ```php
314
     *  $array = [
315
     *      'key' => [
316
     *          'in' => [
317
     *              'val1',
318
     *              'key' => 'val'
319
     *          ]
320
     *      ]
321
     *  ];
322
     * ```
323
     *
324
     * The result of `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
325
     * will be the following:
326
     *
327
     * ```php
328
     *  [
329
     *      'key' => [
330
     *          'in' => [
331
     *              'arr' => 'val'
332
     *          ]
333
     *      ]
334
     *  ]
335
     * ```
336
     *
337
     * @param array $array The array to write the value to.
338
     * @param array|float|int|string|null $key The path of where do you want to write a value to `$array`
339
     * the path can be described by an array of keys. If the path is null then `$array` will be assigned the `$value`.
340
     *
341
     * @psalm-param ArrayKey|null $key
342
     *
343
     * @param mixed $value The value to be written.
344
     */
345 29
    public static function setValue(array &$array, $key, mixed $value): void
346
    {
347 29
        if ($key === null) {
348
            /** @var mixed */
349 2
            $array = $value;
350 2
            return;
351
        }
352
353 27
        $keys = is_array($key) ? $key : [$key];
354
355 27
        while (count($keys) > 1) {
356 15
            $k = self::normalizeArrayKey(array_shift($keys));
357 15
            if (!isset($array[$k])) {
358 8
                $array[$k] = [];
359
            }
360 15
            if (!is_array($array[$k])) {
361 2
                $array[$k] = [$array[$k]];
362
            }
363 15
            $array = &$array[$k];
364
        }
365
366
        /** @var mixed */
367 27
        $array[self::normalizeArrayKey(array_shift($keys))] = $value;
368
    }
369
370
    /**
371
     * Writes a value into an associative array at the key path specified.
372
     * If there is no such key path yet, it will be created recursively.
373
     * If the key exists, it will be overwritten.
374
     *
375
     * ```php
376
     *  $array = [
377
     *      'key' => [
378
     *          'in' => [
379
     *              'val1',
380
     *              'key' => 'val'
381
     *          ]
382
     *      ]
383
     *  ];
384
     * ```
385
     *
386
     * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
387
     *
388
     * ```php
389
     *  [
390
     *      'key' => [
391
     *          'in' => [
392
     *              ['arr' => 'val'],
393
     *              'key' => 'val'
394
     *          ]
395
     *      ]
396
     *  ]
397
     *
398
     * ```
399
     *
400
     * The result of
401
     * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
402
     * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
403
     * will be the following:
404
     *
405
     * ```php
406
     *  [
407
     *      'key' => [
408
     *          'in' => [
409
     *              'arr' => 'val'
410
     *          ]
411
     *      ]
412
     *  ]
413
     * ```
414
     *
415
     * @param array $array The array to write the value to.
416
     * @param array|float|int|string|null $path The path of where do you want to write a value to `$array`.
417
     * The path can be described by a string when each key should be separated by a dot.
418
     * You can also describe the path as an array of keys. If the path is null then `$array` will be assigned
419
     * the `$value`.
420
     * @param mixed $value The value to be written.
421
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
422
     * to "." (dot).
423
     *
424
     * @psalm-param ArrayPath|null $path
425
     */
426 21
    public static function setValueByPath(array &$array, $path, mixed $value, string $delimiter = '.'): void
427
    {
428 21
        self::setValue($array, $path === null ? null : self::parseMixedPath($path, $delimiter), $value);
429
    }
430
431
    /**
432
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
433
     * will be returned instead.
434
     *
435
     * Usage examples,
436
     *
437
     * ```php
438
     * // $array = ['type' => 'A', 'options' => [1, 2]];
439
     *
440
     * // Working with array:
441
     * $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
442
     *
443
     * // $array content
444
     * // $array = ['options' => [1, 2]];
445
     * ```
446
     *
447
     * @param array $array The array to extract value from.
448
     * @param array|float|int|string $key Key name of the array element or associative array at the key path specified.
449
     * @param mixed $default The default value to be returned if the specified key does not exist.
450
     *
451
     * @psalm-param ArrayKey $key
452
     *
453
     * @return mixed The value of the element if found, default value otherwise.
454
     */
455 13
    public static function remove(array &$array, array|float|int|string $key, mixed $default = null)
456
    {
457 13
        $keys = is_array($key) ? $key : [$key];
0 ignored issues
show
introduced by
The condition is_array($key) is always true.
Loading history...
458
459 13
        while (count($keys) > 1) {
460 7
            $key = self::normalizeArrayKey(array_shift($keys));
461 7
            if (!isset($array[$key]) || !is_array($array[$key])) {
462 1
                return $default;
463
            }
464 6
            $array = &$array[$key];
465
        }
466
467 12
        $key = self::normalizeArrayKey(array_shift($keys));
468 12
        if (array_key_exists($key, $array)) {
469
            /** @var mixed */
470 11
            $value = $array[$key];
471 11
            unset($array[$key]);
472 11
            return $value;
473
        }
474
475 1
        return $default;
476
    }
477
478
    /**
479
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
480
     * will be returned instead.
481
     *
482
     * Usage examples,
483
     *
484
     * ```php
485
     * // $array = ['type' => 'A', 'options' => [1, 2]];
486
     *
487
     * // Working with array:
488
     * $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
489
     *
490
     * // $array content
491
     * // $array = ['options' => [1, 2]];
492
     * ```
493
     *
494
     * @param array $array The array to extract value from.
495
     * @param array|float|int|string $path Key name of the array element or associative array at the key path specified.
496
     * The path can be described by a string when each key should be separated by a delimiter (default is dot).
497
     * @param mixed $default The default value to be returned if the specified key does not exist.
498
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
499
     * to "." (dot).
500
     *
501
     * @psalm-param ArrayPath $path
502
     *
503
     * @return mixed The value of the element if found, default value otherwise.
504
     */
505 5
    public static function removeByPath(array &$array, array|float|int|string $path, mixed $default = null, string $delimiter = '.')
506
    {
507 5
        return self::remove($array, self::parseMixedPath($path, $delimiter), $default);
508
    }
509
510
    /**
511
     * Removes items with matching values from the array and returns the removed items.
512
     *
513
     * Example,
514
     *
515
     * ```php
516
     * $array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
517
     * $removed = \Yiisoft\Arrays\ArrayHelper::removeValue($array, 'Jackson');
518
     * // result:
519
     * // $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
520
     * // $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
521
     * ```
522
     *
523
     * @param array $array The array where to look the value from.
524
     * @param mixed $value The value to remove from the array.
525
     *
526
     * @return array The items that were removed from the array.
527
     */
528 2
    public static function removeValue(array &$array, mixed $value): array
529
    {
530 2
        $result = [];
531
        /** @psalm-var mixed $val */
532 2
        foreach ($array as $key => $val) {
533 2
            if ($val === $value) {
534
                /** @var mixed */
535 1
                $result[$key] = $val;
536 1
                unset($array[$key]);
537
            }
538
        }
539
540 2
        return $result;
541
    }
542
543
    /**
544
     * Indexes and/or groups the array according to a specified key.
545
     * The input should be either multidimensional array or an array of objects.
546
     *
547
     * The `$key` can be either a key name of the sub-array, a property name of object, or an anonymous
548
     * function that must return the value that will be used as a key.
549
     *
550
     * `$groups` is an array of keys, that will be used to group the input array into one or more sub-arrays based
551
     * on keys specified.
552
     *
553
     * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
554
     * to `$groups` not specified then the element is discarded.
555
     *
556
     * For example:
557
     *
558
     * ```php
559
     * $array = [
560
     *     ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
561
     *     ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
562
     *     ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
563
     * ];
564
     * $result = ArrayHelper::index($array, 'id');
565
     * ```
566
     *
567
     * The result will be an associative array, where the key is the value of `id` attribute
568
     *
569
     * ```php
570
     * [
571
     *     '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
572
     *     '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
573
     *     // The second element of an original array is overwritten by the last element because of the same id
574
     * ]
575
     * ```
576
     *
577
     * An anonymous function can be used in the grouping array as well.
578
     *
579
     * ```php
580
     * $result = ArrayHelper::index($array, function ($element) {
581
     *     return $element['id'];
582
     * });
583
     * ```
584
     *
585
     * Passing `id` as a third argument will group `$array` by `id`:
586
     *
587
     * ```php
588
     * $result = ArrayHelper::index($array, null, 'id');
589
     * ```
590
     *
591
     * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
592
     * and indexed by `data` on the third level:
593
     *
594
     * ```php
595
     * [
596
     *     '123' => [
597
     *         ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
598
     *     ],
599
     *     '345' => [ // all elements with this index are present in the result array
600
     *         ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
601
     *         ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
602
     *     ]
603
     * ]
604
     * ```
605
     *
606
     * The anonymous function can be used in the array of grouping keys as well:
607
     *
608
     * ```php
609
     * $result = ArrayHelper::index($array, 'data', [function ($element) {
610
     *     return $element['id'];
611
     * }, 'device']);
612
     * ```
613
     *
614
     * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
615
     * and indexed by the `data` on the third level:
616
     *
617
     * ```php
618
     * [
619
     *     '123' => [
620
     *         'laptop' => [
621
     *             'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
622
     *         ]
623
     *     ],
624
     *     '345' => [
625
     *         'tablet' => [
626
     *             'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
627
     *         ],
628
     *         'smartphone' => [
629
     *             'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
630
     *         ]
631
     *     ]
632
     * ]
633
     * ```
634
     *
635
     * @param iterable $array The array or iterable object that needs to be indexed or grouped.
636
     * @param Closure|string|null $key The column name or anonymous function which result will be used
637
     * to index the array.
638
     * @param Closure[]|string|string[]|null $groups The array of keys, that will be used to group the input array
639
     * by one or more keys. If the `$key` attribute or its value for the particular element is null and `$groups` is not
640
     * defined, the array element will be discarded. Otherwise, if `$groups` is specified, array element will be added
641
     * to the result array without any key.
642
     *
643
     * @psalm-param iterable<mixed, array|object> $array
644
     *
645
     * @return array The indexed and/or grouped array.
646
     */
647 24
    public static function index(iterable $array, $key, $groups = []): array
648
    {
649 24
        $result = [];
650 24
        $groups = (array)$groups;
651
652
        /** @var mixed $element */
653 24
        foreach ($array as $element) {
654 24
            if (!is_array($element) && !is_object($element)) {
655 8
                throw new InvalidArgumentException(
656 8
                    'index() can not get value from ' . gettype($element) .
657 8
                    '. The $array should be either multidimensional array or an array of objects.'
658 8
                );
659
            }
660
661 20
            $lastArray = &$result;
662
663 20
            foreach ($groups as $group) {
664 9
                $value = self::normalizeArrayKey(
665 9
                    self::getValue($element, $group)
666 9
                );
667 9
                if (!array_key_exists($value, $lastArray)) {
668 9
                    $lastArray[$value] = [];
669
                }
670 9
                $lastArray = &$lastArray[$value];
671
            }
672
673 20
            if ($key === null) {
674 7
                if (!empty($groups)) {
675 7
                    $lastArray[] = $element;
676
                }
677
            } else {
678
                /** @var mixed */
679 13
                $value = self::getValue($element, $key);
680 13
                if ($value !== null) {
681 12
                    $lastArray[self::normalizeArrayKey($value)] = $element;
682
                }
683
            }
684 20
            unset($lastArray);
685
        }
686
687 16
        return $result;
688
    }
689
690
    /**
691
     * Groups the array according to a specified key.
692
     * This is just an alias for indexing by groups
693
     *
694
     * @param iterable $array The array or iterable object that needs to be grouped.
695
     * @param Closure[]|string|string[] $groups The array of keys, that will be used to group the input array
696
     * by one or more keys.
697
     *
698
     * @psalm-param iterable<mixed, array|object> $array
699
     *
700
     * @return array The grouped array.
701
     */
702 1
    public static function group(iterable $array, array|string $groups): array
703
    {
704 1
        return self::index($array, null, $groups);
705
    }
706
707
    /**
708
     * Returns the values of a specified column in an array.
709
     * The input array should be multidimensional or an array of objects.
710
     *
711
     * For example,
712
     *
713
     * ```php
714
     * $array = [
715
     *     ['id' => '123', 'data' => 'abc'],
716
     *     ['id' => '345', 'data' => 'def'],
717
     * ];
718
     * $result = ArrayHelper::getColumn($array, 'id');
719
     * // the result is: ['123', '345']
720
     *
721
     * // using anonymous function
722
     * $result = ArrayHelper::getColumn($array, function ($element) {
723
     *     return $element['id'];
724
     * });
725
     * ```
726
     *
727
     * @param iterable $array The array or iterable object to get column from.
728
     * @param Closure|string $name Column name or a closure returning column name.
729
     * @param bool $keepKeys Whether to maintain the array keys. If false, the resulting array
730
     * will be re-indexed with integers.
731
     *
732
     * @psalm-param iterable<array-key, array|object> $array
733
     *
734
     * @return array The list of column values.
735
     */
736 8
    public static function getColumn(iterable $array, Closure|string $name, bool $keepKeys = true): array
737
    {
738 8
        $result = [];
739 8
        if ($keepKeys) {
740 6
            foreach ($array as $k => $element) {
741
                /** @var mixed */
742 6
                $result[$k] = self::getValue($element, $name);
743
            }
744
        } else {
745 2
            foreach ($array as $element) {
746
                /** @var mixed */
747 2
                $result[] = self::getValue($element, $name);
748
            }
749
        }
750
751 8
        return $result;
752
    }
753
754
    /**
755
     * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
756
     * The `$from` and `$to` parameters specify the key names or property names to set up the map.
757
     * Optionally, one can further group the map according to a grouping field `$group`.
758
     *
759
     * For example,
760
     *
761
     * ```php
762
     * $array = [
763
     *     ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
764
     *     ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
765
     *     ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
766
     * ];
767
     *
768
     * $result = ArrayHelper::map($array, 'id', 'name');
769
     * // the result is:
770
     * // [
771
     * //     '123' => 'aaa',
772
     * //     '124' => 'bbb',
773
     * //     '345' => 'ccc',
774
     * // ]
775
     *
776
     * $result = ArrayHelper::map($array, 'id', 'name', 'class');
777
     * // the result is:
778
     * // [
779
     * //     'x' => [
780
     * //         '123' => 'aaa',
781
     * //         '124' => 'bbb',
782
     * //     ],
783
     * //     'y' => [
784
     * //         '345' => 'ccc',
785
     * //     ],
786
     * // ]
787
     * ```
788
     *
789
     * @param iterable $array Array or iterable object to build map from.
790
     * @param Closure|string $from Key or property name to map from.
791
     * @param Closure|string $to Key or property name to map to.
792
     * @param Closure|string|null $group Key or property to group the map.
793
     *
794
     * @psalm-param iterable<mixed, array|object> $array
795
     *
796
     * @return array Resulting map.
797
     */
798 9
    public static function map(iterable $array, Closure|string $from, Closure|string $to, $group = null): array
799
    {
800 9
        if ($group === null) {
801 4
            if ($from instanceof Closure || $to instanceof Closure || !is_array($array)) {
802 4
                $result = [];
803 4
                foreach ($array as $element) {
804 4
                    $key = (string)self::getValue($element, $from);
805
                    /** @var mixed */
806 4
                    $result[$key] = self::getValue($element, $to);
807
                }
808
809 4
                return $result;
810
            }
811
812 2
            return array_column($array, $to, $from);
813
        }
814
815 5
        $result = [];
816 5
        foreach ($array as $element) {
817 5
            $groupKey = (string)self::getValue($element, $group);
818 5
            $key = (string)self::getValue($element, $from);
819
            /** @var mixed */
820 5
            $result[$groupKey][$key] = self::getValue($element, $to);
821
        }
822
823 5
        return $result;
824
    }
825
826
    /**
827
     * Checks if the given array contains the specified key.
828
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
829
     * key comparison.
830
     *
831
     * @param array $array The array with keys to check.
832
     * @param array|float|int|string $key The key to check.
833
     * @param bool $caseSensitive Whether the key comparison should be case-sensitive.
834
     *
835
     * @psalm-param ArrayKey $key
836
     *
837
     * @return bool Whether the array contains the specified key.
838
     */
839 41
    public static function keyExists(array $array, array|float|int|string $key, bool $caseSensitive = true): bool
840
    {
841 41
        if (is_array($key)) {
0 ignored issues
show
introduced by
The condition is_array($key) is always true.
Loading history...
842 31
            if (count($key) === 1) {
843 25
                return self::rootKeyExists($array, end($key), $caseSensitive);
844
            }
845
846 27
            foreach (self::getExistsKeys($array, array_shift($key), $caseSensitive) as $existKey) {
847
                /** @var mixed */
848 27
                $array = self::getRootValue($array, $existKey, null);
849 27
                if (is_array($array) && self::keyExists($array, $key, $caseSensitive)) {
850 14
                    return true;
851
                }
852
            }
853
854 13
            return false;
855
        }
856
857 10
        return self::rootKeyExists($array, $key, $caseSensitive);
858
    }
859
860 35
    private static function rootKeyExists(array $array, float|int|string $key, bool $caseSensitive): bool
861
    {
862 35
        $key = (string)$key;
863
864 35
        if ($caseSensitive) {
865 29
            return array_key_exists($key, $array);
866
        }
867
868 6
        foreach (array_keys($array) as $k) {
869 6
            if (strcasecmp($key, (string)$k) === 0) {
870 5
                return true;
871
            }
872
        }
873
874 1
        return false;
875
    }
876
877
    /**
878
     * @return array<int, array-key>
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<int, array-key> at position 4 could not be parsed: Unknown type name 'array-key' at position 4 in array<int, array-key>.
Loading history...
879
     */
880 27
    private static function getExistsKeys(array $array, float|int|string $key, bool $caseSensitive): array
881
    {
882 27
        $key = (string)$key;
883
884 27
        if ($caseSensitive) {
885 22
            return [$key];
886
        }
887
888 5
        return array_filter(
889 5
            array_keys($array),
890 5
            static fn ($k) => strcasecmp($key, (string)$k) === 0
891 5
        );
892
    }
893
894
    /**
895
     * Checks if the given array contains the specified key. The key may be specified in a dot format.
896
     * In particular, if the key is `x.y.z`, then key would be `$array['x']['y']['z']`.
897
     *
898
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
899
     * key comparison.
900
     *
901
     * @param array $array The array to check path in.
902
     * @param array|float|int|string $path The key path. Can be described by a string when each key should be separated
903
     * by delimiter. You can also describe the path as an array of keys.
904
     * @param bool $caseSensitive Whether the key comparison should be case-sensitive.
905
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
906
     * to "." (dot).
907
     *
908
     * @psalm-param ArrayPath $path
909
     */
910 26
    public static function pathExists(
911
        array $array,
912
        array|float|int|string $path,
913
        bool $caseSensitive = true,
914
        string $delimiter = '.'
915
    ): bool {
916 26
        return self::keyExists($array, self::parseMixedPath($path, $delimiter), $caseSensitive);
917
    }
918
919
    /**
920
     * Encodes special characters in an array of strings into HTML entities.
921
     * Only array values will be encoded by default.
922
     * If a value is an array, this method will also encode it recursively.
923
     * Only string values will be encoded.
924
     *
925
     * @param iterable $data Data to be encoded.
926
     * @param bool $valuesOnly Whether to encode array values only. If false,
927
     * both the array keys and array values will be encoded.
928
     * @param string|null $encoding The encoding to use, defaults to `ini_get('default_charset')`.
929
     *
930
     * @psalm-param iterable<mixed, mixed> $data
931
     *
932
     * @return array The encoded data.
933
     *
934
     * @link https://www.php.net/manual/en/function.htmlspecialchars.php
935
     */
936 2
    public static function htmlEncode(iterable $data, bool $valuesOnly = true, string $encoding = null): array
937
    {
938 2
        $d = [];
939
        /**
940
         * @var mixed $key
941
         * @var mixed $value
942
         */
943 2
        foreach ($data as $key => $value) {
944 2
            if (!is_int($key)) {
945 2
                $key = (string)$key;
946
            }
947 2
            if (!$valuesOnly && is_string($key)) {
948 1
                $key = htmlspecialchars($key, ENT_QUOTES|ENT_SUBSTITUTE, $encoding, true);
949
            }
950 2
            if (is_string($value)) {
951 2
                $d[$key] = htmlspecialchars($value, ENT_QUOTES|ENT_SUBSTITUTE, $encoding, true);
952 2
            } elseif (is_array($value)) {
953 2
                $d[$key] = self::htmlEncode($value, $valuesOnly, $encoding);
954
            } else {
955
                /** @var mixed */
956 2
                $d[$key] = $value;
957
            }
958
        }
959
960 2
        return $d;
961
    }
962
963
    /**
964
     * Decodes HTML entities into the corresponding characters in an array of strings.
965
     * Only array values will be decoded by default.
966
     * If a value is an array, this method will also decode it recursively.
967
     * Only string values will be decoded.
968
     *
969
     * @param iterable $data Data to be decoded.
970
     * @param bool $valuesOnly Whether to decode array values only. If false,
971
     * both the array keys and array values will be decoded.
972
     *
973
     * @psalm-param iterable<mixed, mixed> $data
974
     *
975
     * @return array The decoded data.
976
     *
977
     * @link https://www.php.net/manual/en/function.htmlspecialchars-decode.php
978
     */
979 2
    public static function htmlDecode(iterable $data, bool $valuesOnly = true): array
980
    {
981 2
        $decoded = [];
982
        /**
983
         * @var mixed $key
984
         * @var mixed $value
985
         */
986 2
        foreach ($data as $key => $value) {
987 2
            if (!is_int($key)) {
988 2
                $key = (string)$key;
989
            }
990 2
            if (!$valuesOnly && is_string($key)) {
991 1
                $key = htmlspecialchars_decode($key, ENT_QUOTES);
992
            }
993 2
            if (is_string($value)) {
994 2
                $decoded[$key] = htmlspecialchars_decode($value, ENT_QUOTES);
995 2
            } elseif (is_array($value)) {
996 2
                $decoded[$key] = self::htmlDecode($value);
997
            } else {
998
                /** @var mixed */
999 2
                $decoded[$key] = $value;
1000
            }
1001
        }
1002
1003 2
        return $decoded;
1004
    }
1005
1006
    /**
1007
     * Returns a value indicating whether the given array is an associative array.
1008
     *
1009
     * An array is associative if all its keys are strings. If `$allStrings` is false,
1010
     * then an array will be treated as associative if at least one of its keys is a string.
1011
     *
1012
     * Note that an empty array will NOT be considered associative.
1013
     *
1014
     * @param array $array The array being checked.
1015
     * @param bool $allStrings Whether the array keys must be all strings in order for
1016
     * the array to be treated as associative.
1017
     *
1018
     * @return bool Whether the array is associative.
1019
     */
1020 1
    public static function isAssociative(array $array, bool $allStrings = true): bool
1021
    {
1022 1
        if ($array === []) {
1023 1
            return false;
1024
        }
1025
1026 1
        if ($allStrings) {
1027 1
            foreach ($array as $key => $_value) {
1028 1
                if (!is_string($key)) {
1029 1
                    return false;
1030
                }
1031
            }
1032
1033 1
            return true;
1034
        }
1035
1036 1
        foreach ($array as $key => $_value) {
1037 1
            if (is_string($key)) {
1038 1
                return true;
1039
            }
1040
        }
1041
1042 1
        return false;
1043
    }
1044
1045
    /**
1046
     * Returns a value indicating whether the given array is an indexed array.
1047
     *
1048
     * An array is indexed if all its keys are integers. If `$consecutive` is true,
1049
     * then the array keys must be a consecutive sequence starting from 0.
1050
     *
1051
     * Note that an empty array will be considered indexed.
1052
     *
1053
     * @param array $array The array being checked.
1054
     * @param bool $consecutive Whether the array keys must be a consecutive sequence
1055
     * in order for the array to be treated as indexed.
1056
     *
1057
     * @return bool Whether the array is indexed.
1058
     */
1059 1
    public static function isIndexed(array $array, bool $consecutive = false): bool
1060
    {
1061 1
        if ($array === []) {
1062 1
            return true;
1063
        }
1064
1065 1
        if ($consecutive) {
1066 1
            return array_keys($array) === range(0, count($array) - 1);
1067
        }
1068
1069
        /** @psalm-var mixed $value */
1070 1
        foreach ($array as $key => $_value) {
1071 1
            if (!is_int($key)) {
1072 1
                return false;
1073
            }
1074
        }
1075
1076 1
        return true;
1077
    }
1078
1079
    /**
1080
     * Check whether an array or `\Traversable` contains an element.
1081
     *
1082
     * This method does the same as the PHP function {@see in_array()}
1083
     * but additionally works for objects that implement the {@see \Traversable} interface.
1084
     *
1085
     * @param mixed $needle The value to look for.
1086
     * @param iterable $haystack The set of values to search.
1087
     * @param bool $strict Whether to enable strict (`===`) comparison.
1088
     *
1089
     * @throws InvalidArgumentException if `$haystack` is neither traversable nor an array.
1090
     *
1091
     * @return bool `true` if `$needle` was found in `$haystack`, `false` otherwise.
1092
     *
1093
     * @link https://php.net/manual/en/function.in-array.php
1094
     */
1095 3
    public static function isIn(mixed $needle, iterable $haystack, bool $strict = false): bool
1096
    {
1097 3
        if (is_array($haystack)) {
1098 3
            return in_array($needle, $haystack, $strict);
1099
        }
1100
1101
        /** @psalm-var mixed $value */
1102 3
        foreach ($haystack as $value) {
1103 3
            if ($needle == $value && (!$strict || $needle === $value)) {
1104 3
                return true;
1105
            }
1106
        }
1107
1108 3
        return false;
1109
    }
1110
1111
    /**
1112
     * Checks whether an array or {@see \Traversable} is a subset of another array or {@see \Traversable}.
1113
     *
1114
     * This method will return `true`, if all elements of `$needles` are contained in
1115
     * `$haystack`. If at least one element is missing, `false` will be returned.
1116
     *
1117
     * @param iterable $needles The values that must **all** be in `$haystack`.
1118
     * @param iterable $haystack The set of value to search.
1119
     * @param bool $strict Whether to enable strict (`===`) comparison.
1120
     *
1121
     * @throws InvalidArgumentException if `$haystack` or `$needles` is neither traversable nor an array.
1122
     *
1123
     * @return bool `true` if `$needles` is a subset of `$haystack`, `false` otherwise.
1124
     */
1125 1
    public static function isSubset(iterable $needles, iterable $haystack, bool $strict = false): bool
1126
    {
1127
        /** @psalm-var mixed $needle */
1128 1
        foreach ($needles as $needle) {
1129 1
            if (!self::isIn($needle, $haystack, $strict)) {
1130 1
                return false;
1131
            }
1132
        }
1133
1134 1
        return true;
1135
    }
1136
1137
    /**
1138
     * Filters array according to rules specified.
1139
     *
1140
     * For example:
1141
     *
1142
     * ```php
1143
     * $array = [
1144
     *     'A' => [1, 2],
1145
     *     'B' => [
1146
     *         'C' => 1,
1147
     *         'D' => 2,
1148
     *     ],
1149
     *     'E' => 1,
1150
     * ];
1151
     *
1152
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['A']);
1153
     * // $result will be:
1154
     * // [
1155
     * //     'A' => [1, 2],
1156
     * // ]
1157
     *
1158
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['A', 'B.C']);
1159
     * // $result will be:
1160
     * // [
1161
     * //     'A' => [1, 2],
1162
     * //     'B' => ['C' => 1],
1163
     * // ]
1164
     *
1165
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['B', '!B.C']);
1166
     * // $result will be:
1167
     * // [
1168
     * //     'B' => ['D' => 2],
1169
     * // ]
1170
     * ```
1171
     *
1172
     * @param array $array Source array.
1173
     * @param list<string> $filters Rules that define array keys which should be left or removed from results.
0 ignored issues
show
Bug introduced by
The type Yiisoft\Arrays\list was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1174
     * Each rule is:
1175
     * - `var` - `$array['var']` will be left in result.
1176
     * - `var.key` = only `$array['var']['key']` will be left in result.
1177
     * - `!var.key` = `$array['var']['key']` will be removed from result.
1178
     *
1179
     * @return array Filtered array.
1180
     */
1181 17
    public static function filter(array $array, array $filters): array
1182
    {
1183 17
        $result = [];
1184 17
        $excludeFilters = [];
1185
1186 17
        foreach ($filters as $filter) {
1187 17
            if ($filter[0] === '!') {
1188 6
                $excludeFilters[] = substr($filter, 1);
1189 6
                continue;
1190
            }
1191
1192 17
            $nodeValue = $array; // Set $array as root node.
1193 17
            $keys = explode('.', $filter);
1194 17
            foreach ($keys as $key) {
1195 17
                if (!is_array($nodeValue) || !array_key_exists($key, $nodeValue)) {
1196 4
                    continue 2; // Jump to next filter.
1197
                }
1198
                /** @var mixed */
1199 15
                $nodeValue = $nodeValue[$key];
1200
            }
1201
1202
            // We've found a value now let's insert it.
1203 13
            $resultNode = &$result;
1204 13
            foreach ($keys as $key) {
1205 13
                if (!array_key_exists($key, $resultNode)) {
1206 13
                    $resultNode[$key] = [];
1207
                }
1208 13
                $resultNode = &$resultNode[$key];
1209
            }
1210
            /** @var mixed */
1211 13
            $resultNode = $nodeValue;
1212
        }
1213
1214
        /** @var array $result */
1215
1216 17
        foreach ($excludeFilters as $filter) {
1217 6
            $excludeNode = &$result;
1218 6
            $keys = explode('.', $filter);
1219 6
            $numNestedKeys = count($keys) - 1;
1220 6
            foreach ($keys as $i => $key) {
1221 6
                if (!is_array($excludeNode) || !array_key_exists($key, $excludeNode)) {
1222 2
                    continue 2; // Jump to next filter.
1223
                }
1224
1225 5
                if ($i < $numNestedKeys) {
1226
                    /** @var mixed */
1227 5
                    $excludeNode = &$excludeNode[$key];
1228
                } else {
1229 4
                    unset($excludeNode[$key]);
1230 4
                    break;
1231
                }
1232
            }
1233
        }
1234
1235 17
        return $result;
1236
    }
1237
1238
    /**
1239
     * Returns the public member variables of an object.
1240
     *
1241
     * This method is provided such that we can get the public member variables of an object, because a direct call of
1242
     * {@see get_object_vars()} (within the object itself) will return only private and protected variables.
1243
     *
1244
     * @param object $object The object to be handled.
1245
     *
1246
     * @return array|null The public member variables of the object or null if not object given.
1247
     *
1248
     * @link https://www.php.net/manual/en/function.get-object-vars.php
1249
     */
1250 4
    public static function getObjectVars(object $object): ?array
1251
    {
1252 4
        return get_object_vars($object);
1253
    }
1254
1255 142
    private static function normalizeArrayKey(mixed $key): string
1256
    {
1257 142
        return is_float($key) ? NumericHelper::normalize($key) : (string)$key;
1258
    }
1259
1260
    /**
1261
     * @psalm-param ArrayPath $path
1262
     *
1263
     * @psalm-return ArrayKey
1264
     */
1265 86
    private static function parseMixedPath(array|float|int|string $path, string $delimiter): array|float|int|string
1266
    {
1267 86
        if (is_array($path)) {
0 ignored issues
show
introduced by
The condition is_array($path) is always true.
Loading history...
1268 17
            $newPath = [];
1269 17
            foreach ($path as $key) {
1270 17
                if (is_string($key)) {
1271 17
                    $parsedPath = StringHelper::parsePath($key, $delimiter);
1272 17
                    $newPath = array_merge($newPath, $parsedPath);
1273 17
                    continue;
1274
                }
1275
1276 8
                if (is_array($key)) {
1277
                    /** @var list<float|int|string> $parsedPath */
1278 4
                    $parsedPath = self::parseMixedPath($key, $delimiter);
1279 4
                    $newPath = array_merge($newPath, $parsedPath);
0 ignored issues
show
Bug introduced by
$parsedPath of type Yiisoft\Arrays\list is incompatible with the type array expected by parameter $arrays of array_merge(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1279
                    $newPath = array_merge($newPath, /** @scrutinizer ignore-type */ $parsedPath);
Loading history...
1280 4
                    continue;
1281
                }
1282
1283 4
                $newPath[] = $key;
1284
            }
1285 17
            return $newPath;
1286
        }
1287
1288 70
        return is_string($path) ? StringHelper::parsePath($path, $delimiter) : $path;
1289
    }
1290
}
1291