Passed
Pull Request — master (#142)
by Sergei
04:13 queued 01:32
created

ArrayHelper::map()   C

Complexity

Conditions 12
Paths 15

Size

Total Lines 28
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 28
ccs 15
cts 15
cp 1
rs 6.9666
cc 12
nc 15
nop 4
crap 12

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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

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

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

    return false;
}

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

Loading history...
242
                /**
243
                 * This is expected to fail if the property does not exist, or __get() is not implemented.
244
                 * It is not reliably possible to check whether a property is accessible beforehand.
245
                 *
246
                 * @psalm-suppress MixedPropertyFetch
247
                 */
248 14
                return $array->$key;
249
            }
250
        }
251
252
        return $default;
253
    }
254
255 1
    private static function getValueByMatcher(
256
        array $array,
257
        Closure $match,
258
        mixed $default = null
259
    ): mixed
260
    {
261 1
        foreach ($array as $key => $value) {
262 1
            if ($match($value, $key)) {
263 1
                return $value;
264
            }
265
        }
266
267
        return $default;
268
    }
269
270
    /**
271
     * Retrieves the value of an array element or object property with the given key or property name.
272
     * If the key does not exist in the array or object, the default value will be returned instead.
273
     *
274
     * The key may be specified in a dot-separated format to retrieve the value of a sub-array or the property
275
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
276
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
277
     * or `$array->x` is neither an array nor an object, the default value will be returned.
278
     * Note that if the array already has an element `x.y.z`, then its value will be returned
279
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
280
     * like `['x', 'y', 'z']`.
281
     *
282
     * Below are some usage examples,
283
     *
284
     * ```php
285
     * // Using separated format to retrieve the property of embedded object:
286
     * $street = \Yiisoft\Arrays\ArrayHelper::getValue($users, 'address.street');
287
     *
288
     * // Using an array of keys to retrieve the value:
289
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
290
     * ```
291
     *
292
     * @param array|object $array Array or object to extract value from.
293
     * @param array|Closure|float|int|string $path Key name of the array element, an array of keys or property name
294
     * of the object, or an anonymous function returning the value. The anonymous function signature should be:
295
     * `function($array, $defaultValue)`.
296
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
297
     * getting value from an object.
298
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
299
     * to "." (dot).
300
     *
301
     * @psalm-param ArrayPath|Closure $path
302
     *
303
     * @return mixed The value of the element if found, default value otherwise.
304
     */
305 36
    public static function getValueByPath(
306
        array|object $array,
307
        array|Closure|float|int|string $path,
308
        mixed $default = null,
309
        string $delimiter = '.'
310
    ): mixed {
311 36
        return self::getValue(
312 36
            $array,
313 36
            $path instanceof Closure ? $path : self::parseMixedPath($path, $delimiter),
0 ignored issues
show
introduced by
$path is never a sub-type of Closure.
Loading history...
314 36
            $default
315 36
        );
316
    }
317
318
    /**
319
     * Writes a value into an associative array at the key path specified.
320
     * If there is no such key path yet, it will be created recursively.
321
     * If the key exists, it will be overwritten.
322
     *
323
     * ```php
324
     *  $array = [
325
     *      'key' => [
326
     *          'in' => [
327
     *              'val1',
328
     *              'key' => 'val'
329
     *          ]
330
     *      ]
331
     *  ];
332
     * ```
333
     *
334
     * The result of `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
335
     * will be the following:
336
     *
337
     * ```php
338
     *  [
339
     *      'key' => [
340
     *          'in' => [
341
     *              'arr' => 'val'
342
     *          ]
343
     *      ]
344
     *  ]
345
     * ```
346
     *
347
     * @param array $array The array to write the value to.
348
     * @param array|float|int|string|null $key The path of where do you want to write a value to `$array`
349
     * the path can be described by an array of keys. If the path is null then `$array` will be assigned the `$value`.
350
     *
351
     * @psalm-param ArrayKey|null $key
352
     *
353
     * @param mixed $value The value to be written.
354
     */
355 29
    public static function setValue(array &$array, array|float|int|string|null $key, mixed $value): void
356
    {
357 29
        if ($key === null) {
0 ignored issues
show
introduced by
The condition $key === null is always false.
Loading history...
358 2
            $array = $value;
359 2
            return;
360
        }
361
362 27
        $keys = is_array($key) ? $key : [$key];
0 ignored issues
show
introduced by
The condition is_array($key) is always true.
Loading history...
363
364 27
        while (count($keys) > 1) {
365 15
            $k = self::normalizeArrayKey(array_shift($keys));
366 15
            if (!isset($array[$k])) {
367 8
                $array[$k] = [];
368
            }
369 15
            if (!is_array($array[$k])) {
370 2
                $array[$k] = [$array[$k]];
371
            }
372 15
            $array = &$array[$k];
373
            /** @var array $array */
374
        }
375
376 27
        $array[self::normalizeArrayKey(array_shift($keys))] = $value;
377
    }
378
379
    /**
380
     * Find array value in array at the key path specified and add passed value to him.
381
     *
382
     * If there is no such key path yet, it will be created recursively and an empty array will be initialized.
383
     *
384
     * ```php
385
     * $array = ['key' => []];
386
     *
387
     * ArrayHelper::addValue($array, ['key', 'in'], 'variable1');
388
     * ArrayHelper::addValue($array, ['key', 'in'], 'variable2');
389
     *
390
     * // Result: ['key' => ['in' => ['variable1', 'variable2']]]
391
     * ```
392
     *
393
     * If the value exists, it will become the first element of the array.
394
     *
395
     * ```php
396
     * $array = ['key' => 'in'];
397
     *
398
     * ArrayHelper::addValue($array, ['key'], 'variable1');
399
     *
400
     * // Result: ['key' => ['in', 'variable1']]
401
     * ```
402
     *
403
     * @param array $array The array to append the value to.
404
     * @param array|float|int|string|null $key The path of where do you want to append a value to `$array`. The path can
405
     * be described by an array of keys. If the path is null then `$value` will be appended to the `$array`.
406
     *
407
     * @psalm-param ArrayKey|null $key
408
     *
409
     * @param mixed $value The value to be appended.
410
     */
411 31
    public static function addValue(array &$array, array|float|int|string|null $key, mixed $value): void
412
    {
413 31
        if ($key === null) {
0 ignored issues
show
introduced by
The condition $key === null is always false.
Loading history...
414 2
            $array[] = $value;
415 2
            return;
416
        }
417
418 29
        $keys = is_array($key) ? $key : [$key];
0 ignored issues
show
introduced by
The condition is_array($key) is always true.
Loading history...
419
420 29
        while (count($keys) > 0) {
421 29
            $k = self::normalizeArrayKey(array_shift($keys));
422
423 29
            if (!array_key_exists($k, $array)) {
424 20
                $array[$k] = [];
425 14
            } elseif (!is_array($array[$k])) {
426 9
                $array[$k] = [$array[$k]];
427
            }
428
429 29
            $array = &$array[$k];
430
            /** @var array $array */
431
        }
432
433 29
        $array[] = $value;
434
    }
435
436
    /**
437
     * Find array value in array at the key path specified and add passed value to him.
438
     *
439
     * @see addValue
440
     *
441
     * @param array $array The array to append the value to.
442
     * @param array|float|int|string|null $path The path of where do you want to append a value to `$array`. The path
443
     * can be described by a string when each key should be separated by a dot. You can also describe the path as
444
     * an array of keys. If the path is null then `$value` will be appended to the `$array`.
445
     * @param mixed $value The value to be added.
446
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
447
     * to "." (dot).
448
     *
449
     * @psalm-param ArrayPath|null $path
450
     */
451 20
    public static function addValueByPath(
452
        array &$array,
453
        array|float|int|string|null $path,
454
        mixed $value,
455
        string $delimiter = '.'
456
    ): void {
457 20
        self::addValue($array, $path === null ? null : self::parseMixedPath($path, $delimiter), $value);
0 ignored issues
show
introduced by
The condition $path === null is always false.
Loading history...
458
    }
459
460
    /**
461
     * Writes a value into an associative array at the key path specified.
462
     * If there is no such key path yet, it will be created recursively.
463
     * If the key exists, it will be overwritten.
464
     *
465
     * ```php
466
     *  $array = [
467
     *      'key' => [
468
     *          'in' => [
469
     *              'val1',
470
     *              'key' => 'val'
471
     *          ]
472
     *      ]
473
     *  ];
474
     * ```
475
     *
476
     * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
477
     *
478
     * ```php
479
     *  [
480
     *      'key' => [
481
     *          'in' => [
482
     *              ['arr' => 'val'],
483
     *              'key' => 'val'
484
     *          ]
485
     *      ]
486
     *  ]
487
     *
488
     * ```
489
     *
490
     * The result of
491
     * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
492
     * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
493
     * will be the following:
494
     *
495
     * ```php
496
     *  [
497
     *      'key' => [
498
     *          'in' => [
499
     *              'arr' => 'val'
500
     *          ]
501
     *      ]
502
     *  ]
503
     * ```
504
     *
505
     * @param array $array The array to write the value to.
506
     * @param array|float|int|string|null $path The path of where do you want to write a value to `$array`.
507
     * The path can be described by a string when each key should be separated by a dot.
508
     * You can also describe the path as an array of keys. If the path is null then `$array` will be assigned
509
     * the `$value`.
510
     * @param mixed $value The value to be written.
511
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
512
     * to "." (dot).
513
     *
514
     * @psalm-param ArrayPath|null $path
515
     */
516 21
    public static function setValueByPath(
517
        array &$array,
518
        array|float|int|string|null $path,
519
        mixed $value,
520
        string $delimiter = '.'
521
    ): void {
522 21
        self::setValue($array, $path === null ? null : self::parseMixedPath($path, $delimiter), $value);
0 ignored issues
show
introduced by
The condition $path === null is always false.
Loading history...
523
    }
524
525
    /**
526
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
527
     * will be returned instead.
528
     *
529
     * Usage examples,
530
     *
531
     * ```php
532
     * // $array = ['type' => 'A', 'options' => [1, 2]];
533
     *
534
     * // Working with array:
535
     * $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
536
     *
537
     * // $array content
538
     * // $array = ['options' => [1, 2]];
539
     * ```
540
     *
541
     * @param array $array The array to extract value from.
542
     * @param array|float|int|string $key Key name of the array element or associative array at the key path specified.
543
     * @param mixed $default The default value to be returned if the specified key does not exist.
544
     *
545
     * @psalm-param ArrayKey $key
546
     *
547
     * @return mixed The value of the element if found, default value otherwise.
548
     */
549 13
    public static function remove(array &$array, array|float|int|string $key, mixed $default = null): mixed
550
    {
551 13
        $keys = is_array($key) ? $key : [$key];
0 ignored issues
show
introduced by
The condition is_array($key) is always true.
Loading history...
552
553 13
        while (count($keys) > 1) {
554 7
            $key = self::normalizeArrayKey(array_shift($keys));
555 7
            if (!isset($array[$key]) || !is_array($array[$key])) {
556 1
                return $default;
557
            }
558 6
            $array = &$array[$key];
559
        }
560
561 12
        $key = self::normalizeArrayKey(array_shift($keys));
562 12
        if (array_key_exists($key, $array)) {
563 11
            $value = $array[$key];
564 11
            unset($array[$key]);
565 11
            return $value;
566
        }
567
568 1
        return $default;
569
    }
570
571
    /**
572
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
573
     * will be returned instead.
574
     *
575
     * Usage examples,
576
     *
577
     * ```php
578
     * // $array = ['type' => 'A', 'options' => [1, 2]];
579
     *
580
     * // Working with array:
581
     * $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
582
     *
583
     * // $array content
584
     * // $array = ['options' => [1, 2]];
585
     * ```
586
     *
587
     * @param array $array The array to extract value from.
588
     * @param array|float|int|string $path Key name of the array element or associative array at the key path specified.
589
     * The path can be described by a string when each key should be separated by a delimiter (default is dot).
590
     * @param mixed $default The default value to be returned if the specified key does not exist.
591
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
592
     * to "." (dot).
593
     *
594
     * @psalm-param ArrayPath $path
595
     *
596
     * @return mixed The value of the element if found, default value otherwise.
597
     */
598 5
    public static function removeByPath(
599
        array &$array,
600
        array|float|int|string $path,
601
        mixed $default = null,
602
        string $delimiter = '.'
603
    ): mixed {
604 5
        return self::remove($array, self::parseMixedPath($path, $delimiter), $default);
605
    }
606
607
    /**
608
     * Removes items with matching values from the array and returns the removed items.
609
     *
610
     * Example,
611
     *
612
     * ```php
613
     * $array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
614
     * $removed = \Yiisoft\Arrays\ArrayHelper::removeValue($array, 'Jackson');
615
     * // result:
616
     * // $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
617
     * // $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
618
     * ```
619
     *
620
     * @param array $array The array where to look the value from.
621
     * @param mixed $value The value to remove from the array.
622
     *
623
     * @return array The items that were removed from the array.
624
     */
625 2
    public static function removeValue(array &$array, mixed $value): array
626
    {
627 2
        $result = [];
628 2
        foreach ($array as $key => $val) {
629 2
            if ($val === $value) {
630 1
                $result[$key] = $val;
631 1
                unset($array[$key]);
632
            }
633
        }
634
635 2
        return $result;
636
    }
637
638
    /**
639
     * Indexes and/or groups the array according to a specified key.
640
     * The input should be either multidimensional array or an array of objects.
641
     *
642
     * The `$key` can be either a key name of the sub-array, a property name of object, or an anonymous
643
     * function that must return the value that will be used as a key.
644
     *
645
     * `$groups` is an array of keys, that will be used to group the input array into one or more sub-arrays based
646
     * on keys specified.
647
     *
648
     * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
649
     * to `$groups` not specified then the element is discarded.
650
     *
651
     * For example:
652
     *
653
     * ```php
654
     * $array = [
655
     *     ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
656
     *     ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
657
     *     ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
658
     * ];
659
     * $result = ArrayHelper::index($array, 'id');
660
     * ```
661
     *
662
     * The result will be an associative array, where the key is the value of `id` attribute
663
     *
664
     * ```php
665
     * [
666
     *     '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
667
     *     '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
668
     *     // The second element of an original array is overwritten by the last element because of the same id
669
     * ]
670
     * ```
671
     *
672
     * An anonymous function can be used in the grouping array as well.
673
     *
674
     * ```php
675
     * $result = ArrayHelper::index($array, function ($element) {
676
     *     return $element['id'];
677
     * });
678
     * ```
679
     *
680
     * Passing `id` as a third argument will group `$array` by `id`:
681
     *
682
     * ```php
683
     * $result = ArrayHelper::index($array, null, 'id');
684
     * ```
685
     *
686
     * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
687
     * and indexed by `data` on the third level:
688
     *
689
     * ```php
690
     * [
691
     *     '123' => [
692
     *         ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
693
     *     ],
694
     *     '345' => [ // all elements with this index are present in the result array
695
     *         ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
696
     *         ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
697
     *     ]
698
     * ]
699
     * ```
700
     *
701
     * The anonymous function can be used in the array of grouping keys as well:
702
     *
703
     * ```php
704
     * $result = ArrayHelper::index($array, 'data', [function ($element) {
705
     *     return $element['id'];
706
     * }, 'device']);
707
     * ```
708
     *
709
     * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
710
     * and indexed by the `data` on the third level:
711
     *
712
     * ```php
713
     * [
714
     *     '123' => [
715
     *         'laptop' => [
716
     *             'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
717
     *         ]
718
     *     ],
719
     *     '345' => [
720
     *         'tablet' => [
721
     *             'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
722
     *         ],
723
     *         'smartphone' => [
724
     *             'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
725
     *         ]
726
     *     ]
727
     * ]
728
     * ```
729
     *
730
     * @param iterable $array The array or iterable object that needs to be indexed or grouped.
731
     * @param Closure|string|null $key The column name or anonymous function which result will be used
732
     * to index the array.
733
     * @param Closure[]|string|string[]|null $groups The array of keys, that will be used to group the input
734
     * array by one or more keys. If the `$key` attribute or its value for the particular element is null and `$groups`
735
     * is not defined, the array element will be discarded. Otherwise, if `$groups` is specified, array element will be
736
     * added to the result array without any key.
737
     *
738
     * @psalm-param iterable<mixed, array|object> $array
739
     *
740
     * @return array The indexed and/or grouped array.
741
     */
742 24
    public static function index(
743
        iterable $array,
744
        Closure|string|null $key,
745
        array|string|null $groups = []
746
    ): array {
747 24
        $result = [];
748 24
        $groups = (array)$groups;
749
750
        /** @var mixed $element */
751 24
        foreach ($array as $element) {
752 24
            if (!is_array($element) && !is_object($element)) {
753 8
                throw new InvalidArgumentException(
754 8
                    'index() can not get value from ' . gettype($element) .
755 8
                    '. The $array should be either multidimensional array or an array of objects.'
756 8
                );
757
            }
758
759 20
            $lastArray = &$result;
760
761 20
            foreach ($groups as $group) {
762 9
                $value = self::normalizeArrayKey(
763 9
                    self::getValue($element, $group)
764 9
                );
765 9
                if (!array_key_exists($value, $lastArray)) {
766 9
                    $lastArray[$value] = [];
767
                }
768
                /** @psalm-suppress MixedAssignment */
769 9
                $lastArray = &$lastArray[$value];
770
                /** @var array $lastArray */
771
            }
772
773 20
            if ($key === null) {
774 7
                if (!empty($groups)) {
775 7
                    $lastArray[] = $element;
776
                }
777
            } else {
778 13
                $value = $key instanceof Closure ? $key($element) : self::getValue($element, $key);
779 13
                if ($value !== null) {
780 12
                    $lastArray[self::normalizeArrayKey($value)] = $element;
781
                }
782
            }
783 20
            unset($lastArray);
784
        }
785
786 16
        return $result;
787
    }
788
789
    /**
790
     * Groups the array according to a specified key.
791
     * This is just an alias for indexing by groups
792
     *
793
     * @param iterable $array The array or iterable object that needs to be grouped.
794
     * @param Closure[]|string|string[] $groups The array of keys, that will be used to group the input array
795
     * by one or more keys.
796
     *
797
     * @psalm-param iterable<mixed, array|object> $array
798
     *
799
     * @return array The grouped array.
800
     */
801 1
    public static function group(iterable $array, array|string $groups): array
802
    {
803 1
        return self::index($array, null, $groups);
804
    }
805
806
    /**
807
     * Returns the values of a specified column in an array.
808
     * The input array should be multidimensional or an array of objects.
809
     *
810
     * For example,
811
     *
812
     * ```php
813
     * $array = [
814
     *     ['id' => '123', 'data' => 'abc'],
815
     *     ['id' => '345', 'data' => 'def'],
816
     * ];
817
     * $result = ArrayHelper::getColumn($array, 'id');
818
     * // the result is: ['123', '345']
819
     *
820
     * // using anonymous function
821
     * $result = ArrayHelper::getColumn($array, function ($element) {
822
     *     return $element['id'];
823
     * });
824
     * ```
825
     *
826
     * @param iterable $array The array or iterable object to get column from.
827
     * @param Closure|string $name Column name or a closure returning column name.
828
     * @param bool $keepKeys Whether to maintain the array keys. If false, the resulting array
829
     * will be re-indexed with integers.
830
     *
831
     * @psalm-param iterable<array-key, array|object> $array
832
     *
833
     * @return array The list of column values.
834
     */
835 8
    public static function getColumn(iterable $array, Closure|string $name, bool $keepKeys = true): array
836
    {
837 8
        $result = [];
838 8
        if ($keepKeys) {
839 6
            foreach ($array as $k => $element) {
840 6
                $result[$k] = $name instanceof Closure ? $name($element) : self::getValue($element, $name);
841
            }
842
        } else {
843 2
            foreach ($array as $element) {
844 2
                $result[] = $name instanceof Closure ? $name($element) : self::getValue($element, $name);
845
            }
846
        }
847
848 8
        return $result;
849
    }
850
851
    /**
852
     * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
853
     * The `$from` and `$to` parameters specify the key names or property names to set up the map.
854
     * Optionally, one can further group the map according to a grouping field `$group`.
855
     *
856
     * For example,
857
     *
858
     * ```php
859
     * $array = [
860
     *     ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
861
     *     ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
862
     *     ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
863
     * ];
864
     *
865
     * $result = ArrayHelper::map($array, 'id', 'name');
866
     * // the result is:
867
     * // [
868
     * //     '123' => 'aaa',
869
     * //     '124' => 'bbb',
870
     * //     '345' => 'ccc',
871
     * // ]
872
     *
873
     * $result = ArrayHelper::map($array, 'id', 'name', 'class');
874
     * // the result is:
875
     * // [
876
     * //     'x' => [
877
     * //         '123' => 'aaa',
878
     * //         '124' => 'bbb',
879
     * //     ],
880
     * //     'y' => [
881
     * //         '345' => 'ccc',
882
     * //     ],
883
     * // ]
884
     * ```
885
     *
886
     * @param iterable $array Array or iterable object to build map from.
887
     * @param Closure|string $from Key or property name to map from.
888
     * @param Closure|string $to Key or property name to map to.
889
     * @param Closure|string|null $group Key or property to group the map.
890
     *
891
     * @psalm-param iterable<mixed, array|object> $array
892
     *
893
     * @return array Resulting map.
894
     */
895 9
    public static function map(
896
        iterable $array,
897
        Closure|string $from,
898
        Closure|string $to,
899
        Closure|string|null $group = null
900
    ): array {
901 9
        if ($group === null) {
902 4
            if ($from instanceof Closure || $to instanceof Closure || !is_array($array)) {
903 4
                $result = [];
904 4
                foreach ($array as $element) {
905 4
                    $key = (string)($from instanceof Closure ? $from($element) : self::getValue($element, $from));
906 4
                    $result[$key] = $to instanceof Closure ? $to($element) : self::getValue($element, $to);
907
                }
908
909 4
                return $result;
910
            }
911
912 2
            return array_column($array, $to, $from);
913
        }
914
915 5
        $result = [];
916 5
        foreach ($array as $element) {
917 5
            $groupKey = (string)($group instanceof Closure ? $group($element) : self::getValue($element, $group));
918 5
            $key = (string)($from instanceof Closure ? $from($element) : self::getValue($element, $from));
919 5
            $result[$groupKey][$key] = $to instanceof Closure ? $to($element) : self::getValue($element, $to);
920
        }
921
922 5
        return $result;
923
    }
924
925
    /**
926
     * Checks if the given array contains the specified key.
927
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
928
     * key comparison.
929
     *
930
     * @param array $array The array with keys to check.
931
     * @param array|float|int|string $key The key to check.
932
     * @param bool $caseSensitive Whether the key comparison should be case-sensitive.
933
     *
934
     * @psalm-param ArrayKey $key
935
     *
936
     * @return bool Whether the array contains the specified key.
937
     */
938 41
    public static function keyExists(array $array, array|float|int|string $key, bool $caseSensitive = true): bool
939
    {
940 41
        if (is_array($key)) {
0 ignored issues
show
introduced by
The condition is_array($key) is always true.
Loading history...
941 31
            if (count($key) === 1) {
942 25
                return self::rootKeyExists($array, end($key), $caseSensitive);
943
            }
944
945 27
            foreach (self::getExistsKeys($array, array_shift($key), $caseSensitive) as $existKey) {
946 27
                $array = self::getRootValue($array, $existKey, null);
947 27
                if (is_array($array) && self::keyExists($array, $key, $caseSensitive)) {
948 14
                    return true;
949
                }
950
            }
951
952 13
            return false;
953
        }
954
955 10
        return self::rootKeyExists($array, $key, $caseSensitive);
956
    }
957
958 35
    private static function rootKeyExists(array $array, float|int|string $key, bool $caseSensitive): bool
959
    {
960 35
        $key = (string)$key;
961
962 35
        if ($caseSensitive) {
963 29
            return array_key_exists($key, $array);
964
        }
965
966 6
        foreach (array_keys($array) as $k) {
967 6
            if (strcasecmp($key, (string)$k) === 0) {
968 5
                return true;
969
            }
970
        }
971
972 1
        return false;
973
    }
974
975
    /**
976
     * @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...
977
     */
978 27
    private static function getExistsKeys(array $array, float|int|string $key, bool $caseSensitive): array
979
    {
980 27
        $key = (string)$key;
981
982 27
        if ($caseSensitive) {
983 22
            return [$key];
984
        }
985
986 5
        return array_filter(
987 5
            array_keys($array),
988 5
            static fn ($k) => strcasecmp($key, (string)$k) === 0
989 5
        );
990
    }
991
992
    /**
993
     * Checks if the given array contains the specified key. The key may be specified in a dot format.
994
     * In particular, if the key is `x.y.z`, then key would be `$array['x']['y']['z']`.
995
     *
996
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
997
     * key comparison.
998
     *
999
     * @param array $array The array to check path in.
1000
     * @param array|float|int|string $path The key path. Can be described by a string when each key should be separated
1001
     * by delimiter. You can also describe the path as an array of keys.
1002
     * @param bool $caseSensitive Whether the key comparison should be case-sensitive.
1003
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
1004
     * to "." (dot).
1005
     *
1006
     * @psalm-param ArrayPath $path
1007
     */
1008 26
    public static function pathExists(
1009
        array $array,
1010
        array|float|int|string $path,
1011
        bool $caseSensitive = true,
1012
        string $delimiter = '.'
1013
    ): bool {
1014 26
        return self::keyExists($array, self::parseMixedPath($path, $delimiter), $caseSensitive);
1015
    }
1016
1017
    /**
1018
     * Encodes special characters in an array of strings into HTML entities.
1019
     * Only array values will be encoded by default.
1020
     * If a value is an array, this method will also encode it recursively.
1021
     * Only string values will be encoded.
1022
     *
1023
     * @param iterable $data Data to be encoded.
1024
     * @param bool $valuesOnly Whether to encode array values only. If false,
1025
     * both the array keys and array values will be encoded.
1026
     * @param string|null $encoding The encoding to use, defaults to `ini_get('default_charset')`.
1027
     *
1028
     * @psalm-param iterable<mixed, mixed> $data
1029
     *
1030
     * @return array The encoded data.
1031
     *
1032
     * @link https://www.php.net/manual/en/function.htmlspecialchars.php
1033
     */
1034 2
    public static function htmlEncode(iterable $data, bool $valuesOnly = true, string $encoding = null): array
1035
    {
1036 2
        $d = [];
1037 2
        foreach ($data as $key => $value) {
1038 2
            if (!is_int($key)) {
1039 2
                $key = (string)$key;
1040
            }
1041 2
            if (!$valuesOnly && is_string($key)) {
1042 1
                $key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $encoding, true);
1043
            }
1044 2
            if (is_string($value)) {
1045 2
                $d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $encoding, true);
1046 2
            } elseif (is_array($value)) {
1047 2
                $d[$key] = self::htmlEncode($value, $valuesOnly, $encoding);
1048
            } else {
1049 2
                $d[$key] = $value;
1050
            }
1051
        }
1052
1053 2
        return $d;
1054
    }
1055
1056
    /**
1057
     * Decodes HTML entities into the corresponding characters in an array of strings.
1058
     * Only array values will be decoded by default.
1059
     * If a value is an array, this method will also decode it recursively.
1060
     * Only string values will be decoded.
1061
     *
1062
     * @param iterable $data Data to be decoded.
1063
     * @param bool $valuesOnly Whether to decode array values only. If false,
1064
     * both the array keys and array values will be decoded.
1065
     *
1066
     * @psalm-param iterable<mixed, mixed> $data
1067
     *
1068
     * @return array The decoded data.
1069
     *
1070
     * @link https://www.php.net/manual/en/function.htmlspecialchars-decode.php
1071
     */
1072 2
    public static function htmlDecode(iterable $data, bool $valuesOnly = true): array
1073
    {
1074 2
        $decoded = [];
1075 2
        foreach ($data as $key => $value) {
1076 2
            if (!is_int($key)) {
1077 2
                $key = (string)$key;
1078
            }
1079 2
            if (!$valuesOnly && is_string($key)) {
1080 1
                $key = htmlspecialchars_decode($key, ENT_QUOTES);
1081
            }
1082 2
            if (is_string($value)) {
1083 2
                $decoded[$key] = htmlspecialchars_decode($value, ENT_QUOTES);
1084 2
            } elseif (is_array($value)) {
1085 2
                $decoded[$key] = self::htmlDecode($value);
1086
            } else {
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 1
        foreach ($array as $key => $_value) {
1158 1
            if (!is_int($key)) {
1159 1
                return false;
1160
            }
1161
        }
1162
1163 1
        return true;
1164
    }
1165
1166
    /**
1167
     * Check whether an array or `\Traversable` contains an element.
1168
     *
1169
     * This method does the same as the PHP function {@see in_array()}
1170
     * but additionally works for objects that implement the {@see \Traversable} interface.
1171
     *
1172
     * @param mixed $needle The value to look for.
1173
     * @param iterable $haystack The set of values to search.
1174
     * @param bool $strict Whether to enable strict (`===`) comparison.
1175
     *
1176
     * @throws InvalidArgumentException if `$haystack` is neither traversable nor an array.
1177
     *
1178
     * @return bool `true` if `$needle` was found in `$haystack`, `false` otherwise.
1179
     *
1180
     * @link https://php.net/manual/en/function.in-array.php
1181
     */
1182 3
    public static function isIn(mixed $needle, iterable $haystack, bool $strict = false): bool
1183
    {
1184 3
        if (is_array($haystack)) {
1185 3
            return in_array($needle, $haystack, $strict);
1186
        }
1187
1188 3
        foreach ($haystack as $value) {
1189 3
            if ($needle == $value && (!$strict || $needle === $value)) {
1190 3
                return true;
1191
            }
1192
        }
1193
1194 3
        return false;
1195
    }
1196
1197
    /**
1198
     * Checks whether an array or {@see \Traversable} is a subset of another array or {@see \Traversable}.
1199
     *
1200
     * This method will return `true`, if all elements of `$needles` are contained in
1201
     * `$haystack`. If at least one element is missing, `false` will be returned.
1202
     *
1203
     * @param iterable $needles The values that must **all** be in `$haystack`.
1204
     * @param iterable $haystack The set of value to search.
1205
     * @param bool $strict Whether to enable strict (`===`) comparison.
1206
     *
1207
     * @throws InvalidArgumentException if `$haystack` or `$needles` is neither traversable nor an array.
1208
     *
1209
     * @return bool `true` if `$needles` is a subset of `$haystack`, `false` otherwise.
1210
     */
1211 1
    public static function isSubset(iterable $needles, iterable $haystack, bool $strict = false): bool
1212
    {
1213 1
        foreach ($needles as $needle) {
1214 1
            if (!self::isIn($needle, $haystack, $strict)) {
1215 1
                return false;
1216
            }
1217
        }
1218
1219 1
        return true;
1220
    }
1221
1222
    /**
1223
     * Filters array according to rules specified.
1224
     *
1225
     * For example:
1226
     *
1227
     * ```php
1228
     * $array = [
1229
     *     'A' => [1, 2],
1230
     *     'B' => [
1231
     *         'C' => 1,
1232
     *         'D' => 2,
1233
     *     ],
1234
     *     'E' => 1,
1235
     * ];
1236
     *
1237
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['A']);
1238
     * // $result will be:
1239
     * // [
1240
     * //     'A' => [1, 2],
1241
     * // ]
1242
     *
1243
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['A', 'B.C']);
1244
     * // $result will be:
1245
     * // [
1246
     * //     'A' => [1, 2],
1247
     * //     'B' => ['C' => 1],
1248
     * // ]
1249
     *
1250
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['B', '!B.C']);
1251
     * // $result will be:
1252
     * // [
1253
     * //     'B' => ['D' => 2],
1254
     * // ]
1255
     * ```
1256
     *
1257
     * @param array $array Source array.
1258
     * @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...
1259
     * Each rule is:
1260
     * - `var` - `$array['var']` will be left in result.
1261
     * - `var.key` = only `$array['var']['key']` will be left in result.
1262
     * - `!var.key` = `$array['var']['key']` will be removed from result.
1263
     *
1264
     * @return array Filtered array.
1265
     */
1266 17
    public static function filter(array $array, array $filters): array
1267
    {
1268 17
        $result = [];
1269 17
        $excludeFilters = [];
1270
1271 17
        foreach ($filters as $filter) {
1272 17
            if ($filter[0] === '!') {
1273 6
                $excludeFilters[] = substr($filter, 1);
1274 6
                continue;
1275
            }
1276
1277 17
            $nodeValue = $array; // Set $array as root node.
1278 17
            $keys = explode('.', $filter);
1279 17
            foreach ($keys as $key) {
1280 17
                if (!is_array($nodeValue) || !array_key_exists($key, $nodeValue)) {
1281 4
                    continue 2; // Jump to next filter.
1282
                }
1283 15
                $nodeValue = $nodeValue[$key];
1284
            }
1285
1286
            // We've found a value now let's insert it.
1287 13
            $resultNode = &$result;
1288 13
            foreach ($keys as $key) {
1289 13
                if (!array_key_exists($key, $resultNode)) {
1290 13
                    $resultNode[$key] = [];
1291
                }
1292
                /** @psalm-suppress MixedAssignment */
1293 13
                $resultNode = &$resultNode[$key];
1294
                /** @var array $resultNode */
1295
            }
1296
            /** @var array */
1297 13
            $resultNode = $nodeValue;
1298
        }
1299
1300
        /**
1301
         * @psalm-suppress UnnecessaryVarAnnotation
1302
         *
1303
         * @var array $result
1304
         */
1305
1306 17
        foreach ($excludeFilters as $filter) {
1307 6
            $excludeNode = &$result;
1308 6
            $keys = explode('.', $filter);
1309 6
            $numNestedKeys = count($keys) - 1;
1310 6
            foreach ($keys as $i => $key) {
1311 6
                if (!is_array($excludeNode) || !array_key_exists($key, $excludeNode)) {
1312 2
                    continue 2; // Jump to next filter.
1313
                }
1314
1315 5
                if ($i < $numNestedKeys) {
1316
                    /** @psalm-suppress MixedAssignment */
1317 5
                    $excludeNode = &$excludeNode[$key];
1318
                } else {
1319 4
                    unset($excludeNode[$key]);
1320 4
                    break;
1321
                }
1322
            }
1323
        }
1324
1325
        /** @var array $result */
1326
1327 17
        return $result;
1328
    }
1329
1330
    /**
1331
     * Returns the public member variables of an object.
1332
     *
1333
     * This method is provided such that we can get the public member variables of an object, because a direct call of
1334
     * {@see get_object_vars()} (within the object itself) will return only private and protected variables.
1335
     *
1336
     * @param object $object The object to be handled.
1337
     *
1338
     * @return array The public member variables of the object.
1339
     *
1340
     * @link https://www.php.net/manual/en/function.get-object-vars.php
1341
     */
1342 4
    public static function getObjectVars(object $object): array
1343
    {
1344 4
        return get_object_vars($object);
1345
    }
1346
1347
    /**
1348
     * @param array[] $arrays
1349
     */
1350 9
    private static function doMerge(array $arrays, ?int $depth, int $currentDepth = 0): array
1351
    {
1352 9
        $result = array_shift($arrays) ?: [];
1353 9
        while (!empty($arrays)) {
1354 8
            foreach (array_shift($arrays) as $key => $value) {
1355 8
                if (is_int($key)) {
1356 6
                    if (array_key_exists($key, $result)) {
1357 6
                        if ($result[$key] !== $value) {
1358 6
                            $result[] = $value;
1359
                        }
1360
                    } else {
1361 6
                        $result[$key] = $value;
1362
                    }
1363
                } elseif (
1364 6
                    isset($result[$key])
1365 6
                    && ($depth === null || $currentDepth < $depth)
1366 6
                    && is_array($value)
1367 6
                    && is_array($result[$key])
1368
                ) {
1369 5
                    $result[$key] = self::doMerge([$result[$key], $value], $depth, $currentDepth + 1);
1370
                } else {
1371 6
                    $result[$key] = $value;
1372
                }
1373
            }
1374
        }
1375 9
        return $result;
1376
    }
1377
1378 171
    private static function normalizeArrayKey(mixed $key): string
1379
    {
1380 171
        return is_float($key) ? NumericHelper::normalize($key) : (string)$key;
1381
    }
1382
1383
    /**
1384
     * @psalm-param ArrayPath $path
1385
     *
1386
     * @psalm-return ArrayKey
1387
     */
1388 105
    private static function parseMixedPath(array|float|int|string $path, string $delimiter): array|float|int|string
1389
    {
1390 105
        if (is_array($path)) {
0 ignored issues
show
introduced by
The condition is_array($path) is always true.
Loading history...
1391 19
            $newPath = [];
1392 19
            foreach ($path as $key) {
1393 19
                if (is_string($key)) {
1394 19
                    $parsedPath = StringHelper::parsePath($key, $delimiter);
1395 19
                    $newPath = array_merge($newPath, $parsedPath);
1396 19
                    continue;
1397
                }
1398
1399 9
                if (is_array($key)) {
1400
                    /** @var list<float|int|string> $parsedPath */
1401 5
                    $parsedPath = self::parseMixedPath($key, $delimiter);
1402 5
                    $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

1402
                    $newPath = array_merge($newPath, /** @scrutinizer ignore-type */ $parsedPath);
Loading history...
1403 5
                    continue;
1404
                }
1405
1406 4
                $newPath[] = $key;
1407
            }
1408 19
            return $newPath;
1409
        }
1410
1411 87
        return is_string($path) ? StringHelper::parsePath($path, $delimiter) : $path;
1412
    }
1413
}
1414