Passed
Pull Request — master (#137)
by
unknown
09:02 queued 06:43
created

ArrayHelper::addValue()   A

Complexity

Conditions 6
Paths 11

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6

Importance

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

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

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

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

    return false;
}

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

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

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