Passed
Push — master ( ff29fb...0214e4 )
by Sergei
03:08 queued 15s
created

ArrayHelper::addValue()   A

Complexity

Conditions 6
Paths 9

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6

Importance

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

1395
                    $newPath = array_merge($newPath, /** @scrutinizer ignore-type */ $parsedPath);
Loading history...
1396 5
                    continue;
1397
                }
1398
1399 4
                $newPath[] = $key;
1400
            }
1401 19
            return $newPath;
1402
        }
1403
1404 87
        return is_string($path) ? StringHelper::parsePath($path, $delimiter) : $path;
1405
    }
1406
}
1407