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

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