Passed
Pull Request — master (#121)
by Sergei
14:06
created

ArrayHelper   F

Complexity

Total Complexity 155

Size/Duplication

Total Lines 1301
Duplicated Lines 0 %

Test Coverage

Coverage 99.35%

Importance

Changes 12
Bugs 0 Features 0
Metric Value
wmc 155
eloc 284
c 12
b 0
f 0
dl 0
loc 1301
ccs 306
cts 308
cp 0.9935
rs 2

28 Methods

Rating   Name   Duplication   Size   Complexity  
A removeByPath() 0 3 1
C toArray() 0 55 15
B merge() 0 25 10
B getValue() 0 27 8
C filter() 0 55 13
A getExistsKeys() 0 11 2
B isAssociative() 0 23 7
A setValue() 0 23 6
A pathExists() 0 7 1
A isIn() 0 14 6
A getObjectVars() 0 3 1
A getValueByPath() 0 6 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 setValueByPath() 0 3 2
A removeValue() 0 13 3
A normalizeArrayKey() 0 3 2
A isSubset() 0 10 3
B getRootValue() 0 39 11
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 get_class;
16
use function gettype;
17
use function in_array;
18
use function is_array;
19
use function is_float;
20
use function is_int;
21
use function is_object;
22
use function is_string;
23
24
/**
25
 * Yii array helper provides static methods allowing you to deal with arrays more efficiently.
26
 *
27
 * @psalm-type ArrayKey = float|int|string|array<array-key,float|int|string>
28
 * @psalm-type ArrayPath = float|int|string|array<array-key,float|int|string|array<array-key,float|int|string>>
29
 */
30
final class ArrayHelper
31
{
32
    /**
33
     * Converts an object or an array of objects into an array.
34
     *
35
     * For example:
36
     *
37
     * ```php
38
     * [
39
     *     Post::class => [
40
     *         'id',
41
     *         'title',
42
     *         'createTime' => 'created_at',
43
     *         'length' => function ($post) {
44
     *             return strlen($post->content);
45
     *         },
46
     *     ],
47
     * ]
48
     * ```
49
     *
50
     * The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
51
     *
52
     * ```php
53
     * [
54
     *     'id' => 123,
55
     *     'title' => 'test',
56
     *     'createTime' => '2013-01-01 12:00AM',
57
     *     'length' => 301,
58
     * ]
59
     * ```
60
     *
61
     * @param array|object|string $object The object to be converted into an array.
62
     *
63
     * It is possible to provide default way of converting object to array for a specific class by implementing
64
     * {@see \Yiisoft\Arrays\ArrayableInterface} in its class.
65
     * @param array $properties A mapping from object class names to the properties that need to put into
66
     * the resulting arrays. The properties specified for each class is an array of the following format:
67
     *
68
     * - A field name to include as is.
69
     * - A key-value pair of desired array key name and model column name to take value from.
70
     * - A key-value pair of desired array key name and a callback which returns value.
71
     * @param bool $recursive Whether to recursively converts properties which are objects into arrays.
72
     *
73
     * @return array The array representation of the object.
74
     */
75 6
    public static function toArray($object, array $properties = [], bool $recursive = true): array
76
    {
77 6
        if (is_array($object)) {
78 5
            if ($recursive) {
79
                /** @var mixed $value */
80 4
                foreach ($object as $key => $value) {
81 4
                    if (is_array($value) || is_object($value)) {
82 4
                        $object[$key] = self::toArray($value, $properties);
83
                    }
84
                }
85
            }
86
87 5
            return $object;
88
        }
89
90 4
        if (is_object($object)) {
91 4
            if (!empty($properties)) {
92 1
                $className = get_class($object);
93 1
                if (!empty($properties[$className])) {
94 1
                    $result = [];
95
                    /**
96
                     * @var int|string $key
97
                     * @var string $name
98
                     */
99 1
                    foreach ($properties[$className] as $key => $name) {
100 1
                        if (is_int($key)) {
101
                            /** @var mixed */
102 1
                            $result[$name] = $object->$name;
103
                        } else {
104
                            /** @var mixed */
105 1
                            $result[$key] = self::getValue($object, $name);
106
                        }
107
                    }
108
109 1
                    return $recursive ? self::toArray($result, $properties) : $result;
110
                }
111
            }
112 4
            if ($object instanceof ArrayableInterface) {
113 3
                $result = $object->toArray([], [], $recursive);
114
            } else {
115 4
                $result = [];
116
                /**
117
                 * @var string $key
118
                 * @var mixed $value
119
                 */
120 4
                foreach ($object as $key => $value) {
121
                    /** @var mixed */
122 4
                    $result[$key] = $value;
123
                }
124
            }
125
126 4
            return $recursive ? self::toArray($result, $properties) : $result;
127
        }
128
129 1
        return [$object];
130
    }
131
132
    /**
133
     * Merges two or more arrays into one recursively.
134
     * If each array has an element with the same string key value, the latter
135
     * will overwrite the former (different from {@see array_merge_recursive()}).
136
     * Recursive merging will be conducted if both arrays have an element of array
137
     * type and are having the same key.
138
     * For integer-keyed elements, the elements from the latter array will
139
     * be appended to the former array.
140
     *
141
     * @param array ...$arrays Arrays to be merged.
142
     *
143
     * @return array The merged array (the original arrays are not changed).
144
     */
145 4
    public static function merge(...$arrays): array
146
    {
147 4
        $result = array_shift($arrays) ?: [];
148 4
        while (!empty($arrays)) {
149
            /** @var mixed $value */
150 3
            foreach (array_shift($arrays) as $key => $value) {
151 3
                if (is_int($key)) {
152 3
                    if (array_key_exists($key, $result)) {
153 3
                        if ($result[$key] !== $value) {
154
                            /** @var mixed */
155 3
                            $result[] = $value;
156
                        }
157
                    } else {
158
                        /** @var mixed */
159 3
                        $result[$key] = $value;
160
                    }
161 1
                } elseif (isset($result[$key]) && is_array($value) && is_array($result[$key])) {
162 1
                    $result[$key] = self::merge($result[$key], $value);
163
                } else {
164
                    /** @var mixed */
165 1
                    $result[$key] = $value;
166
                }
167
            }
168
        }
169 4
        return $result;
170
    }
171
172
    /**
173
     * Retrieves the value of an array element or object property with the given key or property name.
174
     * If the key does not exist in the array or object, the default value will be returned instead.
175
     *
176
     * Below are some usage examples,
177
     *
178
     * ```php
179
     * // Working with array:
180
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($_POST, 'username');
181
     *
182
     * // Working with object:
183
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($user, 'username');
184
     *
185
     * // Working with anonymous function:
186
     * $fullName = \Yiisoft\Arrays\ArrayHelper::getValue($user, function ($user, $defaultValue) {
187
     *     return $user->firstName . ' ' . $user->lastName;
188
     * });
189
     *
190
     * // Using an array of keys to retrieve the value:
191
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
192
     * ```
193
     *
194
     * @param array|object $array Array or object to extract value from.
195
     * @param array|Closure|float|int|string $key Key name of the array element,
196
     * an array of keys or property name of the object, or an anonymous function
197
     * returning the value. The anonymous function signature should be:
198
     * `function($array, $defaultValue)`.
199
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
200
     * getting value from an object.
201
     *
202
     * @psalm-param ArrayKey|Closure $key
203
     *
204
     * @return mixed The value of the element if found, default value otherwise.
205
     */
206 96
    public static function getValue($array, $key, $default = null)
207
    {
208 96
        if ($key instanceof Closure) {
209 16
            return $key($array, $default);
210
        }
211
212
        /** @psalm-suppress DocblockTypeContradiction */
213 88
        if (!is_array($array) && !is_object($array)) {
214 1
            throw new InvalidArgumentException(
215 1
                'getValue() can not get value from ' . gettype($array) . '. Only array and object are supported.'
216 1
            );
217
        }
218
219 87
        if (is_array($key)) {
220
            /** @psalm-var array<mixed,string|int> $key */
221 42
            $lastKey = array_pop($key);
222 42
            foreach ($key as $keyPart) {
223
                /** @var mixed */
224 39
                $array = self::getRootValue($array, $keyPart, null);
225 39
                if (!is_array($array) && !is_object($array)) {
226 10
                    return $default;
227
                }
228
            }
229 33
            return self::getRootValue($array, $lastKey, $default);
230
        }
231
232 47
        return self::getRootValue($array, $key, $default);
233
    }
234
235
    /**
236
     * @param mixed $array Array or object to extract value from, otherwise method will return $default.
237
     * @param float|int|string $key Key name of the array element or property name of the object.
238
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
239
     * getting value from an object.
240
     *
241
     * @return mixed The value of the element if found, default value otherwise.
242
     */
243 114
    private static function getRootValue($array, $key, $default)
244
    {
245 114
        if (is_array($array)) {
246 101
            $key = self::normalizeArrayKey($key);
247 101
            return array_key_exists($key, $array) ? $array[$key] : $default;
248
        }
249
250 15
        if (is_object($array)) {
251
            try {
252 15
                return $array::$$key;
253 15
            } catch (Throwable $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Throwable $e) 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...
254 15
                $useDefault = false;
255 15
                set_error_handler(
256 15
                    static function (int $errorNumber, string $errorString) use ($array, $key, &$useDefault): bool {
257
                        if (
258 4
                            $errorNumber === (PHP_VERSION_ID >= 80000 ? E_WARNING : E_NOTICE)
259
                            && (
260 4
                                $errorString === 'Undefined property: ' . get_class($array) . '::$' . $key
261 4
                                || $errorString === (
262 4
                                    PHP_VERSION_ID >= 80000
263 2
                                    ? 'Undefined array key "' . $key . '"'
264 4
                                    : 'Undefined index: ' . $key
265 4
                                )
266
                            )
267
                        ) {
268 4
                            $useDefault = true;
269 4
                            return true;
270
                        }
271
                        return false;
272 15
                    }
273 15
                );
274
                /** @var mixed $value */
275 15
                $value = $array->$key;
276 14
                restore_error_handler();
277 14
                return $useDefault ? $default : $value;
278
            }
279
        }
280
281
        return $default;
282
    }
283
284
    /**
285
     * Retrieves the value of an array element or object property with the given key or property name.
286
     * If the key does not exist in the array or object, the default value will be returned instead.
287
     *
288
     * The key may be specified in a dot-separated format to retrieve the value of a sub-array or the property
289
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
290
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
291
     * or `$array->x` is neither an array nor an object, the default value will be returned.
292
     * Note that if the array already has an element `x.y.z`, then its value will be returned
293
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
294
     * like `['x', 'y', 'z']`.
295
     *
296
     * Below are some usage examples,
297
     *
298
     * ```php
299
     * // Using separated format to retrieve the property of embedded object:
300
     * $street = \Yiisoft\Arrays\ArrayHelper::getValue($users, 'address.street');
301
     *
302
     * // Using an array of keys to retrieve the value:
303
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
304
     * ```
305
     *
306
     * @param array|object $array Array or object to extract value from.
307
     * @param array|Closure|float|int|string $path Key name of the array element, an array of keys or property name
308
     * of the object, or an anonymous function returning the value. The anonymous function signature should be:
309
     * `function($array, $defaultValue)`.
310
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
311
     * getting value from an object.
312
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
313
     * to "." (dot).
314
     *
315
     * @psalm-param ArrayPath|Closure $path
316
     *
317
     * @return mixed The value of the element if found, default value otherwise.
318
     */
319 37
    public static function getValueByPath($array, $path, $default = null, string $delimiter = '.')
320
    {
321 37
        return self::getValue(
322 37
            $array,
323 37
            $path instanceof Closure ? $path : self::parseMixedPath($path, $delimiter),
324 37
            $default
325 37
        );
326
    }
327
328
    /**
329
     * Writes a value into an associative array at the key path specified.
330
     * If there is no such key path yet, it will be created recursively.
331
     * If the key exists, it will be overwritten.
332
     *
333
     * ```php
334
     *  $array = [
335
     *      'key' => [
336
     *          'in' => [
337
     *              'val1',
338
     *              'key' => 'val'
339
     *          ]
340
     *      ]
341
     *  ];
342
     * ```
343
     *
344
     * The result of `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
345
     * will be the following:
346
     *
347
     * ```php
348
     *  [
349
     *      'key' => [
350
     *          'in' => [
351
     *              'arr' => 'val'
352
     *          ]
353
     *      ]
354
     *  ]
355
     * ```
356
     *
357
     * @param array $array The array to write the value to.
358
     * @param array|float|int|string|null $key The path of where do you want to write a value to `$array`
359
     * the path can be described by an array of keys. If the path is null then `$array` will be assigned the `$value`.
360
     *
361
     * @psalm-param ArrayKey|null $key
362
     *
363
     * @param mixed $value The value to be written.
364
     */
365 29
    public static function setValue(array &$array, $key, $value): void
366
    {
367 29
        if ($key === null) {
368
            /** @var mixed */
369 2
            $array = $value;
370 2
            return;
371
        }
372
373 27
        $keys = is_array($key) ? $key : [$key];
374
375 27
        while (count($keys) > 1) {
376 15
            $k = self::normalizeArrayKey(array_shift($keys));
377 15
            if (!isset($array[$k])) {
378 8
                $array[$k] = [];
379
            }
380 15
            if (!is_array($array[$k])) {
381 2
                $array[$k] = [$array[$k]];
382
            }
383 15
            $array = &$array[$k];
384
        }
385
386
        /** @var mixed */
387 27
        $array[self::normalizeArrayKey(array_shift($keys))] = $value;
388
    }
389
390
    /**
391
     * Writes a value into an associative array at the key path specified.
392
     * If there is no such key path yet, it will be created recursively.
393
     * If the key exists, it will be overwritten.
394
     *
395
     * ```php
396
     *  $array = [
397
     *      'key' => [
398
     *          'in' => [
399
     *              'val1',
400
     *              'key' => 'val'
401
     *          ]
402
     *      ]
403
     *  ];
404
     * ```
405
     *
406
     * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
407
     *
408
     * ```php
409
     *  [
410
     *      'key' => [
411
     *          'in' => [
412
     *              ['arr' => 'val'],
413
     *              'key' => 'val'
414
     *          ]
415
     *      ]
416
     *  ]
417
     *
418
     * ```
419
     *
420
     * The result of
421
     * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
422
     * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
423
     * will be the following:
424
     *
425
     * ```php
426
     *  [
427
     *      'key' => [
428
     *          'in' => [
429
     *              'arr' => 'val'
430
     *          ]
431
     *      ]
432
     *  ]
433
     * ```
434
     *
435
     * @param array $array The array to write the value to.
436
     * @param array|float|int|string|null $path The path of where do you want to write a value to `$array`.
437
     * The path can be described by a string when each key should be separated by a dot.
438
     * You can also describe the path as an array of keys. If the path is null then `$array` will be assigned
439
     * the `$value`.
440
     * @param mixed $value The value to be written.
441
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
442
     * to "." (dot).
443
     *
444
     * @psalm-param ArrayPath|null $path
445
     */
446 21
    public static function setValueByPath(array &$array, $path, $value, string $delimiter = '.'): void
447
    {
448 21
        self::setValue($array, $path === null ? null : self::parseMixedPath($path, $delimiter), $value);
449
    }
450
451
    /**
452
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
453
     * will be returned instead.
454
     *
455
     * Usage examples,
456
     *
457
     * ```php
458
     * // $array = ['type' => 'A', 'options' => [1, 2]];
459
     *
460
     * // Working with array:
461
     * $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
462
     *
463
     * // $array content
464
     * // $array = ['options' => [1, 2]];
465
     * ```
466
     *
467
     * @param array $array The array to extract value from.
468
     * @param array|float|int|string $key Key name of the array element or associative array at the key path specified.
469
     * @param mixed $default The default value to be returned if the specified key does not exist.
470
     *
471
     * @psalm-param ArrayKey $key
472
     *
473
     * @return mixed The value of the element if found, default value otherwise.
474
     */
475 13
    public static function remove(array &$array, $key, $default = null)
476
    {
477 13
        $keys = is_array($key) ? $key : [$key];
478
479 13
        while (count($keys) > 1) {
480 7
            $key = self::normalizeArrayKey(array_shift($keys));
481 7
            if (!isset($array[$key]) || !is_array($array[$key])) {
482 1
                return $default;
483
            }
484 6
            $array = &$array[$key];
485
        }
486
487 12
        $key = self::normalizeArrayKey(array_shift($keys));
488 12
        if (array_key_exists($key, $array)) {
489
            /** @var mixed */
490 11
            $value = $array[$key];
491 11
            unset($array[$key]);
492 11
            return $value;
493
        }
494
495 1
        return $default;
496
    }
497
498
    /**
499
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
500
     * will be returned instead.
501
     *
502
     * Usage examples,
503
     *
504
     * ```php
505
     * // $array = ['type' => 'A', 'options' => [1, 2]];
506
     *
507
     * // Working with array:
508
     * $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
509
     *
510
     * // $array content
511
     * // $array = ['options' => [1, 2]];
512
     * ```
513
     *
514
     * @param array $array The array to extract value from.
515
     * @param array|float|int|string $path Key name of the array element or associative array at the key path specified.
516
     * The path can be described by a string when each key should be separated by a delimiter (default is dot).
517
     * @param mixed $default The default value to be returned if the specified key does not exist.
518
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
519
     * to "." (dot).
520
     *
521
     * @psalm-param ArrayPath $path
522
     *
523
     * @return mixed The value of the element if found, default value otherwise.
524
     */
525 5
    public static function removeByPath(array &$array, $path, $default = null, string $delimiter = '.')
526
    {
527 5
        return self::remove($array, self::parseMixedPath($path, $delimiter), $default);
528
    }
529
530
    /**
531
     * Removes items with matching values from the array and returns the removed items.
532
     *
533
     * Example,
534
     *
535
     * ```php
536
     * $array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
537
     * $removed = \Yiisoft\Arrays\ArrayHelper::removeValue($array, 'Jackson');
538
     * // result:
539
     * // $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
540
     * // $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
541
     * ```
542
     *
543
     * @param array $array The array where to look the value from.
544
     * @param mixed $value The value to remove from the array.
545
     *
546
     * @return array The items that were removed from the array.
547
     */
548 2
    public static function removeValue(array &$array, $value): array
549
    {
550 2
        $result = [];
551
        /** @psalm-var mixed $val */
552 2
        foreach ($array as $key => $val) {
553 2
            if ($val === $value) {
554
                /** @var mixed */
555 1
                $result[$key] = $val;
556 1
                unset($array[$key]);
557
            }
558
        }
559
560 2
        return $result;
561
    }
562
563
    /**
564
     * Indexes and/or groups the array according to a specified key.
565
     * The input should be either multidimensional array or an array of objects.
566
     *
567
     * The `$key` can be either a key name of the sub-array, a property name of object, or an anonymous
568
     * function that must return the value that will be used as a key.
569
     *
570
     * `$groups` is an array of keys, that will be used to group the input array into one or more sub-arrays based
571
     * on keys specified.
572
     *
573
     * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
574
     * to `$groups` not specified then the element is discarded.
575
     *
576
     * For example:
577
     *
578
     * ```php
579
     * $array = [
580
     *     ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
581
     *     ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
582
     *     ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
583
     * ];
584
     * $result = ArrayHelper::index($array, 'id');
585
     * ```
586
     *
587
     * The result will be an associative array, where the key is the value of `id` attribute
588
     *
589
     * ```php
590
     * [
591
     *     '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
592
     *     '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
593
     *     // The second element of an original array is overwritten by the last element because of the same id
594
     * ]
595
     * ```
596
     *
597
     * An anonymous function can be used in the grouping array as well.
598
     *
599
     * ```php
600
     * $result = ArrayHelper::index($array, function ($element) {
601
     *     return $element['id'];
602
     * });
603
     * ```
604
     *
605
     * Passing `id` as a third argument will group `$array` by `id`:
606
     *
607
     * ```php
608
     * $result = ArrayHelper::index($array, null, 'id');
609
     * ```
610
     *
611
     * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
612
     * and indexed by `data` on the third level:
613
     *
614
     * ```php
615
     * [
616
     *     '123' => [
617
     *         ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
618
     *     ],
619
     *     '345' => [ // all elements with this index are present in the result array
620
     *         ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
621
     *         ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
622
     *     ]
623
     * ]
624
     * ```
625
     *
626
     * The anonymous function can be used in the array of grouping keys as well:
627
     *
628
     * ```php
629
     * $result = ArrayHelper::index($array, 'data', [function ($element) {
630
     *     return $element['id'];
631
     * }, 'device']);
632
     * ```
633
     *
634
     * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
635
     * and indexed by the `data` on the third level:
636
     *
637
     * ```php
638
     * [
639
     *     '123' => [
640
     *         'laptop' => [
641
     *             'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
642
     *         ]
643
     *     ],
644
     *     '345' => [
645
     *         'tablet' => [
646
     *             'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
647
     *         ],
648
     *         'smartphone' => [
649
     *             'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
650
     *         ]
651
     *     ]
652
     * ]
653
     * ```
654
     *
655
     * @param iterable $array The array or iterable object that needs to be indexed or grouped.
656
     * @param Closure|string|null $key The column name or anonymous function which result will be used
657
     * to index the array.
658
     * @param Closure[]|string|string[]|null $groups The array of keys, that will be used to group the input array
659
     * by one or more keys. If the `$key` attribute or its value for the particular element is null and `$groups` is not
660
     * defined, the array element will be discarded. Otherwise, if `$groups` is specified, array element will be added
661
     * to the result array without any key.
662
     *
663
     * @psalm-param iterable<mixed, array|object> $array
664
     *
665
     * @return array The indexed and/or grouped array.
666
     */
667 24
    public static function index(iterable $array, $key, $groups = []): array
668
    {
669 24
        $result = [];
670 24
        $groups = (array)$groups;
671
672
        /** @var mixed $element */
673 24
        foreach ($array as $element) {
674 24
            if (!is_array($element) && !is_object($element)) {
675 8
                throw new InvalidArgumentException(
676 8
                    'index() can not get value from ' . gettype($element) .
677 8
                    '. The $array should be either multidimensional array or an array of objects.'
678 8
                );
679
            }
680
681 20
            $lastArray = &$result;
682
683 20
            foreach ($groups as $group) {
684 9
                $value = self::normalizeArrayKey(
685 9
                    self::getValue($element, $group)
686 9
                );
687 9
                if (!array_key_exists($value, $lastArray)) {
688 9
                    $lastArray[$value] = [];
689
                }
690 9
                $lastArray = &$lastArray[$value];
691
            }
692
693 20
            if ($key === null) {
694 7
                if (!empty($groups)) {
695 7
                    $lastArray[] = $element;
696
                }
697
            } else {
698
                /** @var mixed */
699 13
                $value = self::getValue($element, $key);
700 13
                if ($value !== null) {
701 12
                    $lastArray[self::normalizeArrayKey($value)] = $element;
702
                }
703
            }
704 20
            unset($lastArray);
705
        }
706
707 16
        return $result;
708
    }
709
710
    /**
711
     * Groups the array according to a specified key.
712
     * This is just an alias for indexing by groups
713
     *
714
     * @param iterable $array The array or iterable object that needs to be grouped.
715
     * @param Closure[]|string|string[] $groups The array of keys, that will be used to group the input array
716
     * by one or more keys.
717
     *
718
     * @psalm-param iterable<mixed, array|object> $array
719
     *
720
     * @return array The grouped array.
721
     */
722 1
    public static function group(iterable $array, $groups): array
723
    {
724 1
        return self::index($array, null, $groups);
725
    }
726
727
    /**
728
     * Returns the values of a specified column in an array.
729
     * The input array should be multidimensional or an array of objects.
730
     *
731
     * For example,
732
     *
733
     * ```php
734
     * $array = [
735
     *     ['id' => '123', 'data' => 'abc'],
736
     *     ['id' => '345', 'data' => 'def'],
737
     * ];
738
     * $result = ArrayHelper::getColumn($array, 'id');
739
     * // the result is: ['123', '345']
740
     *
741
     * // using anonymous function
742
     * $result = ArrayHelper::getColumn($array, function ($element) {
743
     *     return $element['id'];
744
     * });
745
     * ```
746
     *
747
     * @param iterable $array The array or iterable object to get column from.
748
     * @param Closure|string $name Column name or a closure returning column name.
749
     * @param bool $keepKeys Whether to maintain the array keys. If false, the resulting array
750
     * will be re-indexed with integers.
751
     *
752
     * @psalm-param iterable<array-key, array|object> $array
753
     *
754
     * @return array The list of column values.
755
     */
756 8
    public static function getColumn(iterable $array, $name, bool $keepKeys = true): array
757
    {
758 8
        $result = [];
759 8
        if ($keepKeys) {
760 6
            foreach ($array as $k => $element) {
761
                /** @var mixed */
762 6
                $result[$k] = self::getValue($element, $name);
763
            }
764
        } else {
765 2
            foreach ($array as $element) {
766
                /** @var mixed */
767 2
                $result[] = self::getValue($element, $name);
768
            }
769
        }
770
771 8
        return $result;
772
    }
773
774
    /**
775
     * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
776
     * The `$from` and `$to` parameters specify the key names or property names to set up the map.
777
     * Optionally, one can further group the map according to a grouping field `$group`.
778
     *
779
     * For example,
780
     *
781
     * ```php
782
     * $array = [
783
     *     ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
784
     *     ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
785
     *     ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
786
     * ];
787
     *
788
     * $result = ArrayHelper::map($array, 'id', 'name');
789
     * // the result is:
790
     * // [
791
     * //     '123' => 'aaa',
792
     * //     '124' => 'bbb',
793
     * //     '345' => 'ccc',
794
     * // ]
795
     *
796
     * $result = ArrayHelper::map($array, 'id', 'name', 'class');
797
     * // the result is:
798
     * // [
799
     * //     'x' => [
800
     * //         '123' => 'aaa',
801
     * //         '124' => 'bbb',
802
     * //     ],
803
     * //     'y' => [
804
     * //         '345' => 'ccc',
805
     * //     ],
806
     * // ]
807
     * ```
808
     *
809
     * @param iterable $array Array or iterable object to build map from.
810
     * @param Closure|string $from Key or property name to map from.
811
     * @param Closure|string $to Key or property name to map to.
812
     * @param Closure|string|null $group Key or property to group the map.
813
     *
814
     * @psalm-param iterable<mixed, array|object> $array
815
     *
816
     * @return array Resulting map.
817
     */
818 9
    public static function map(iterable $array, $from, $to, $group = null): array
819
    {
820 9
        if ($group === null) {
821 4
            if ($from instanceof Closure || $to instanceof Closure || !is_array($array)) {
822 4
                $result = [];
823 4
                foreach ($array as $element) {
824 4
                    $key = (string)self::getValue($element, $from);
825
                    /** @var mixed */
826 4
                    $result[$key] = self::getValue($element, $to);
827
                }
828
829 4
                return $result;
830
            }
831
832 2
            return array_column($array, $to, $from);
833
        }
834
835 5
        $result = [];
836 5
        foreach ($array as $element) {
837 5
            $groupKey = (string)self::getValue($element, $group);
838 5
            $key = (string)self::getValue($element, $from);
839
            /** @var mixed */
840 5
            $result[$groupKey][$key] = self::getValue($element, $to);
841
        }
842
843 5
        return $result;
844
    }
845
846
    /**
847
     * Checks if the given array contains the specified key.
848
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
849
     * key comparison.
850
     *
851
     * @param array $array The array with keys to check.
852
     * @param array|float|int|string $key The key to check.
853
     * @param bool $caseSensitive Whether the key comparison should be case-sensitive.
854
     *
855
     * @psalm-param ArrayKey $key
856
     *
857
     * @return bool Whether the array contains the specified key.
858
     */
859 41
    public static function keyExists(array $array, $key, bool $caseSensitive = true): bool
860
    {
861 41
        if (is_array($key)) {
862 31
            if (count($key) === 1) {
863 25
                return self::rootKeyExists($array, end($key), $caseSensitive);
864
            }
865
866 27
            foreach (self::getExistsKeys($array, array_shift($key), $caseSensitive) as $existKey) {
867
                /** @var mixed */
868 27
                $array = self::getRootValue($array, $existKey, null);
869 27
                if (is_array($array) && self::keyExists($array, $key, $caseSensitive)) {
870 14
                    return true;
871
                }
872
            }
873
874 13
            return false;
875
        }
876
877 10
        return self::rootKeyExists($array, $key, $caseSensitive);
878
    }
879
880
    /**
881
     * @param array $array
882
     * @param float|int|string $key
883
     * @param bool $caseSensitive
884
     *
885
     * @return bool
886
     */
887 35
    private static function rootKeyExists(array $array, $key, bool $caseSensitive): bool
888
    {
889 35
        $key = (string)$key;
890
891 35
        if ($caseSensitive) {
892 29
            return array_key_exists($key, $array);
893
        }
894
895 6
        foreach (array_keys($array) as $k) {
896 6
            if (strcasecmp($key, (string)$k) === 0) {
897 5
                return true;
898
            }
899
        }
900
901 1
        return false;
902
    }
903
904
    /**
905
     * @param array $array
906
     * @param float|int|string $key
907
     * @param bool $caseSensitive
908
     *
909
     * @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...
910
     */
911 27
    private static function getExistsKeys(array $array, $key, bool $caseSensitive): array
912
    {
913 27
        $key = (string)$key;
914
915 27
        if ($caseSensitive) {
916 22
            return [$key];
917
        }
918
919 5
        return array_filter(
920 5
            array_keys($array),
921 5
            static fn ($k) => strcasecmp($key, (string)$k) === 0
922 5
        );
923
    }
924
925
    /**
926
     * Checks if the given array contains the specified key. The key may be specified in a dot format.
927
     * In particular, if the key is `x.y.z`, then key would be `$array['x']['y']['z']`.
928
     *
929
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
930
     * key comparison.
931
     *
932
     * @param array $array The array to check path in.
933
     * @param array|float|int|string $path The key path. Can be described by a string when each key should be separated
934
     * by delimiter. You can also describe the path as an array of keys.
935
     * @param bool $caseSensitive Whether the key comparison should be case-sensitive.
936
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
937
     * to "." (dot).
938
     *
939
     * @psalm-param ArrayPath $path
940
     *
941
     * @return bool
942
     */
943 26
    public static function pathExists(
944
        array $array,
945
        $path,
946
        bool $caseSensitive = true,
947
        string $delimiter = '.'
948
    ): bool {
949 26
        return self::keyExists($array, self::parseMixedPath($path, $delimiter), $caseSensitive);
950
    }
951
952
    /**
953
     * Encodes special characters in an array of strings into HTML entities.
954
     * Only array values will be encoded by default.
955
     * If a value is an array, this method will also encode it recursively.
956
     * Only string values will be encoded.
957
     *
958
     * @param iterable $data Data to be encoded.
959
     * @param bool $valuesOnly Whether to encode array values only. If false,
960
     * both the array keys and array values will be encoded.
961
     * @param string|null $encoding The encoding to use, defaults to `ini_get('default_charset')`.
962
     *
963
     * @psalm-param iterable<mixed, mixed> $data
964
     *
965
     * @return array The encoded data.
966
     *
967
     * @link https://www.php.net/manual/en/function.htmlspecialchars.php
968
     */
969 2
    public static function htmlEncode(iterable $data, bool $valuesOnly = true, string $encoding = null): array
970
    {
971 2
        $d = [];
972
        /**
973
         * @var mixed $key
974
         * @var mixed $value
975
         */
976 2
        foreach ($data as $key => $value) {
977 2
            if (!is_int($key)) {
978 2
                $key = (string)$key;
979
            }
980 2
            if (!$valuesOnly && is_string($key)) {
981 1
                $key = htmlspecialchars($key, ENT_QUOTES|ENT_SUBSTITUTE, $encoding, true);
982
            }
983 2
            if (is_string($value)) {
984 2
                $d[$key] = htmlspecialchars($value, ENT_QUOTES|ENT_SUBSTITUTE, $encoding, true);
985 2
            } elseif (is_array($value)) {
986 2
                $d[$key] = self::htmlEncode($value, $valuesOnly, $encoding);
987
            } else {
988
                /** @var mixed */
989 2
                $d[$key] = $value;
990
            }
991
        }
992
993 2
        return $d;
994
    }
995
996
    /**
997
     * Decodes HTML entities into the corresponding characters in an array of strings.
998
     * Only array values will be decoded by default.
999
     * If a value is an array, this method will also decode it recursively.
1000
     * Only string values will be decoded.
1001
     *
1002
     * @param iterable $data Data to be decoded.
1003
     * @param bool $valuesOnly Whether to decode array values only. If false,
1004
     * both the array keys and array values will be decoded.
1005
     *
1006
     * @psalm-param iterable<mixed, mixed> $data
1007
     *
1008
     * @return array The decoded data.
1009
     *
1010
     * @link https://www.php.net/manual/en/function.htmlspecialchars-decode.php
1011
     */
1012 2
    public static function htmlDecode(iterable $data, bool $valuesOnly = true): array
1013
    {
1014 2
        $decoded = [];
1015
        /**
1016
         * @var mixed $key
1017
         * @var mixed $value
1018
         */
1019 2
        foreach ($data as $key => $value) {
1020 2
            if (!is_int($key)) {
1021 2
                $key = (string)$key;
1022
            }
1023 2
            if (!$valuesOnly && is_string($key)) {
1024 1
                $key = htmlspecialchars_decode($key, ENT_QUOTES);
1025
            }
1026 2
            if (is_string($value)) {
1027 2
                $decoded[$key] = htmlspecialchars_decode($value, ENT_QUOTES);
1028 2
            } elseif (is_array($value)) {
1029 2
                $decoded[$key] = self::htmlDecode($value);
1030
            } else {
1031
                /** @var mixed */
1032 2
                $decoded[$key] = $value;
1033
            }
1034
        }
1035
1036 2
        return $decoded;
1037
    }
1038
1039
    /**
1040
     * Returns a value indicating whether the given array is an associative array.
1041
     *
1042
     * An array is associative if all its keys are strings. If `$allStrings` is false,
1043
     * then an array will be treated as associative if at least one of its keys is a string.
1044
     *
1045
     * Note that an empty array will NOT be considered associative.
1046
     *
1047
     * @param array $array The array being checked.
1048
     * @param bool $allStrings Whether the array keys must be all strings in order for
1049
     * the array to be treated as associative.
1050
     *
1051
     * @return bool Whether the array is associative.
1052
     */
1053 1
    public static function isAssociative(array $array, bool $allStrings = true): bool
1054
    {
1055 1
        if ($array === []) {
1056 1
            return false;
1057
        }
1058
1059 1
        if ($allStrings) {
1060 1
            foreach ($array as $key => $_value) {
1061 1
                if (!is_string($key)) {
1062 1
                    return false;
1063
                }
1064
            }
1065
1066 1
            return true;
1067
        }
1068
1069 1
        foreach ($array as $key => $_value) {
1070 1
            if (is_string($key)) {
1071 1
                return true;
1072
            }
1073
        }
1074
1075 1
        return false;
1076
    }
1077
1078
    /**
1079
     * Returns a value indicating whether the given array is an indexed array.
1080
     *
1081
     * An array is indexed if all its keys are integers. If `$consecutive` is true,
1082
     * then the array keys must be a consecutive sequence starting from 0.
1083
     *
1084
     * Note that an empty array will be considered indexed.
1085
     *
1086
     * @param array $array The array being checked.
1087
     * @param bool $consecutive Whether the array keys must be a consecutive sequence
1088
     * in order for the array to be treated as indexed.
1089
     *
1090
     * @return bool Whether the array is indexed.
1091
     */
1092 1
    public static function isIndexed(array $array, bool $consecutive = false): bool
1093
    {
1094 1
        if ($array === []) {
1095 1
            return true;
1096
        }
1097
1098 1
        if ($consecutive) {
1099 1
            return array_keys($array) === range(0, count($array) - 1);
1100
        }
1101
1102
        /** @psalm-var mixed $value */
1103 1
        foreach ($array as $key => $_value) {
1104 1
            if (!is_int($key)) {
1105 1
                return false;
1106
            }
1107
        }
1108
1109 1
        return true;
1110
    }
1111
1112
    /**
1113
     * Check whether an array or `\Traversable` contains an element.
1114
     *
1115
     * This method does the same as the PHP function {@see in_array()}
1116
     * but additionally works for objects that implement the {@see \Traversable} interface.
1117
     *
1118
     * @param mixed $needle The value to look for.
1119
     * @param iterable $haystack The set of values to search.
1120
     * @param bool $strict Whether to enable strict (`===`) comparison.
1121
     *
1122
     * @throws InvalidArgumentException if `$haystack` is neither traversable nor an array.
1123
     *
1124
     * @return bool `true` if `$needle` was found in `$haystack`, `false` otherwise.
1125
     *
1126
     * @link https://php.net/manual/en/function.in-array.php
1127
     */
1128 3
    public static function isIn($needle, iterable $haystack, bool $strict = false): bool
1129
    {
1130 3
        if (is_array($haystack)) {
1131 3
            return in_array($needle, $haystack, $strict);
1132
        }
1133
1134
        /** @psalm-var mixed $value */
1135 3
        foreach ($haystack as $value) {
1136 3
            if ($needle == $value && (!$strict || $needle === $value)) {
1137 3
                return true;
1138
            }
1139
        }
1140
1141 3
        return false;
1142
    }
1143
1144
    /**
1145
     * Checks whether an array or {@see \Traversable} is a subset of another array or {@see \Traversable}.
1146
     *
1147
     * This method will return `true`, if all elements of `$needles` are contained in
1148
     * `$haystack`. If at least one element is missing, `false` will be returned.
1149
     *
1150
     * @param iterable $needles The values that must **all** be in `$haystack`.
1151
     * @param iterable $haystack The set of value to search.
1152
     * @param bool $strict Whether to enable strict (`===`) comparison.
1153
     *
1154
     * @throws InvalidArgumentException if `$haystack` or `$needles` is neither traversable nor an array.
1155
     *
1156
     * @return bool `true` if `$needles` is a subset of `$haystack`, `false` otherwise.
1157
     */
1158 1
    public static function isSubset(iterable $needles, iterable $haystack, bool $strict = false): bool
1159
    {
1160
        /** @psalm-var mixed $needle */
1161 1
        foreach ($needles as $needle) {
1162 1
            if (!self::isIn($needle, $haystack, $strict)) {
1163 1
                return false;
1164
            }
1165
        }
1166
1167 1
        return true;
1168
    }
1169
1170
    /**
1171
     * Filters array according to rules specified.
1172
     *
1173
     * For example:
1174
     *
1175
     * ```php
1176
     * $array = [
1177
     *     'A' => [1, 2],
1178
     *     'B' => [
1179
     *         'C' => 1,
1180
     *         'D' => 2,
1181
     *     ],
1182
     *     'E' => 1,
1183
     * ];
1184
     *
1185
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['A']);
1186
     * // $result will be:
1187
     * // [
1188
     * //     'A' => [1, 2],
1189
     * // ]
1190
     *
1191
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['A', 'B.C']);
1192
     * // $result will be:
1193
     * // [
1194
     * //     'A' => [1, 2],
1195
     * //     'B' => ['C' => 1],
1196
     * // ]
1197
     *
1198
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['B', '!B.C']);
1199
     * // $result will be:
1200
     * // [
1201
     * //     'B' => ['D' => 2],
1202
     * // ]
1203
     * ```
1204
     *
1205
     * @param array $array Source array.
1206
     * @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...
1207
     * Each rule is:
1208
     * - `var` - `$array['var']` will be left in result.
1209
     * - `var.key` = only `$array['var']['key']` will be left in result.
1210
     * - `!var.key` = `$array['var']['key']` will be removed from result.
1211
     *
1212
     * @return array Filtered array.
1213
     */
1214 17
    public static function filter(array $array, array $filters): array
1215
    {
1216 17
        $result = [];
1217 17
        $excludeFilters = [];
1218
1219 17
        foreach ($filters as $filter) {
1220 17
            if ($filter[0] === '!') {
1221 6
                $excludeFilters[] = substr($filter, 1);
1222 6
                continue;
1223
            }
1224
1225 17
            $nodeValue = $array; // Set $array as root node.
1226 17
            $keys = explode('.', $filter);
1227 17
            foreach ($keys as $key) {
1228 17
                if (!is_array($nodeValue) || !array_key_exists($key, $nodeValue)) {
1229 4
                    continue 2; // Jump to next filter.
1230
                }
1231
                /** @var mixed */
1232 15
                $nodeValue = $nodeValue[$key];
1233
            }
1234
1235
            // We've found a value now let's insert it.
1236 13
            $resultNode = &$result;
1237 13
            foreach ($keys as $key) {
1238 13
                if (!array_key_exists($key, $resultNode)) {
1239 13
                    $resultNode[$key] = [];
1240
                }
1241 13
                $resultNode = &$resultNode[$key];
1242
            }
1243
            /** @var mixed */
1244 13
            $resultNode = $nodeValue;
1245
        }
1246
1247
        /** @var array $result */
1248
1249 17
        foreach ($excludeFilters as $filter) {
1250 6
            $excludeNode = &$result;
1251 6
            $keys = explode('.', $filter);
1252 6
            $numNestedKeys = count($keys) - 1;
1253 6
            foreach ($keys as $i => $key) {
1254 6
                if (!is_array($excludeNode) || !array_key_exists($key, $excludeNode)) {
1255 2
                    continue 2; // Jump to next filter.
1256
                }
1257
1258 5
                if ($i < $numNestedKeys) {
1259
                    /** @var mixed */
1260 5
                    $excludeNode = &$excludeNode[$key];
1261
                } else {
1262 4
                    unset($excludeNode[$key]);
1263 4
                    break;
1264
                }
1265
            }
1266
        }
1267
1268 17
        return $result;
1269
    }
1270
1271
    /**
1272
     * Returns the public member variables of an object.
1273
     *
1274
     * This method is provided such that we can get the public member variables of an object, because a direct call of
1275
     * {@see get_object_vars()} (within the object itself) will return only private and protected variables.
1276
     *
1277
     * @param object $object The object to be handled.
1278
     *
1279
     * @return array|null The public member variables of the object or null if not object given.
1280
     *
1281
     * @link https://www.php.net/manual/en/function.get-object-vars.php
1282
     */
1283 4
    public static function getObjectVars(object $object): ?array
1284
    {
1285 4
        return get_object_vars($object);
1286
    }
1287
1288
    /**
1289
     * @param mixed $key
1290
     *
1291
     * @return string
1292
     */
1293 142
    private static function normalizeArrayKey($key): string
1294
    {
1295 142
        return is_float($key) ? NumericHelper::normalize($key) : (string)$key;
1296
    }
1297
1298
    /**
1299
     * @param array|float|int|string $path
1300
     * @param string $delimiter
1301
     *
1302
     * @psalm-param ArrayPath $path
1303
     *
1304
     * @return array|float|int|string
1305
     * @psalm-return ArrayKey
1306
     */
1307 86
    private static function parseMixedPath($path, string $delimiter)
1308
    {
1309 86
        if (is_array($path)) {
1310 17
            $newPath = [];
1311 17
            foreach ($path as $key) {
1312 17
                if (is_string($key)) {
1313 17
                    $parsedPath = StringHelper::parsePath($key, $delimiter);
1314 17
                    $newPath = array_merge($newPath, $parsedPath);
1315 17
                    continue;
1316
                }
1317
1318 8
                if (is_array($key)) {
1319
                    /** @var list<float|int|string> $parsedPath */
1320 4
                    $parsedPath = self::parseMixedPath($key, $delimiter);
1321 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

1321
                    $newPath = array_merge($newPath, /** @scrutinizer ignore-type */ $parsedPath);
Loading history...
1322 4
                    continue;
1323
                }
1324
1325 4
                $newPath[] = $key;
1326
            }
1327 17
            return $newPath;
1328
        }
1329
1330 70
        return is_string($path) ? StringHelper::parsePath($path, $delimiter) : $path;
1331
    }
1332
}
1333