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

1450
                    $newPath = array_merge($newPath, /** @scrutinizer ignore-type */ $parsedPath);
Loading history...
1451 5
                    continue;
1452
                }
1453
1454 4
                $newPath[] = $key;
1455
            }
1456 19
            return $newPath;
1457
        }
1458
1459 87
        return is_string($path) ? StringHelper::parsePath($path, $delimiter) : $path;
1460
    }
1461
}
1462