Passed
Pull Request — master (#114)
by Sergei
02:27
created

ArrayHelper::parseMixedPath()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6

Importance

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

1376
                    $newPath = array_merge($newPath, /** @scrutinizer ignore-type */ $parsedPath);
Loading history...
1377 4
                    continue;
1378
                }
1379
1380 4
                $newPath[] = $key;
1381
            }
1382 17
            return $newPath;
1383
        }
1384
1385 70
        return is_string($path) ? self::parsePath($path, $delimiter) : $path;
1386
    }
1387
}
1388