Passed
Pull Request — master (#137)
by
unknown
03:05
created

ArrayHelper::addValueByPath()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 7
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

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

1467
                    $newPath = array_merge($newPath, /** @scrutinizer ignore-type */ $parsedPath);
Loading history...
1468 5
                    continue;
1469
                }
1470
1471 4
                $newPath[] = $key;
1472
            }
1473 19
            return $newPath;
1474
        }
1475
1476 87
        return is_string($path) ? StringHelper::parsePath($path, $delimiter) : $path;
1477
    }
1478
}
1479