Passed
Pull Request — master (#142)
by
unknown
02:32
created

ArrayHelper::getValueByMatcher()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

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

1406
                    $newPath = array_merge($newPath, /** @scrutinizer ignore-type */ $parsedPath);
Loading history...
1407 5
                    continue;
1408
                }
1409
1410 4
                $newPath[] = $key;
1411
            }
1412 19
            return $newPath;
1413
        }
1414
1415 87
        return is_string($path) ? StringHelper::parsePath($path, $delimiter) : $path;
1416
    }
1417
}
1418