Passed
Pull Request — master (#111)
by
unknown
02:19
created

ArrayHelper   F

Complexity

Total Complexity 154

Size/Duplication

Total Lines 1303
Duplicated Lines 0 %

Test Coverage

Coverage 99.66%

Importance

Changes 15
Bugs 0 Features 0
Metric Value
wmc 154
eloc 278
c 15
b 0
f 0
dl 0
loc 1303
ccs 290
cts 291
cp 0.9966
rs 2

28 Methods

Rating   Name   Duplication   Size   Complexity  
A setValue() 0 23 6
A getValueByPath() 0 6 2
C toArray() 0 55 15
B getValue() 0 27 8
A setValueByPath() 0 3 2
B merge() 0 25 10
A getRootValue() 0 18 5
C filter() 0 55 13
A getExistsKeys() 0 11 2
B isAssociative() 0 23 7
A pathExists() 0 7 1
A isIn() 0 14 6
A getObjectVars() 0 3 1
A isIndexed() 0 18 5
B index() 0 41 9
B htmlDecode() 0 25 7
A group() 0 3 1
A remove() 0 21 6
A keyExists() 0 19 6
A removeByPath() 0 3 1
A getColumn() 0 16 4
A rootKeyExists() 0 15 4
B htmlEncode() 0 25 7
B map() 0 26 7
A removeValue() 0 13 3
A normalizeArrayKey() 0 3 2
A isSubset() 0 10 3
B parsePath() 0 40 11

How to fix   Complexity   

Complex Class

Complex classes like ArrayHelper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ArrayHelper, and based on these observations, apply Extract Interface, too.

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
12
use function array_key_exists;
13
use function count;
14
use function get_class;
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
use function preg_match_all;
23
use function sprintf;
24
use function str_replace;
25
use function strlen;
26
27
/**
28
 * Yii array helper provides static methods allowing you to deal with arrays more efficiently.
29
 *
30
 * @psalm-type ArrayKey = float|int|string|array<array-key,float|int|string>
31
 * @psalm-type ArrayPath = float|int|string|array<array-key,float|int|string|array<array-key,float|int|string>>
32
 */
33
final class ArrayHelper
34
{
35
    /**
36
     * Converts an object or an array of objects into an array.
37
     *
38
     * For example:
39
     *
40
     * ```php
41
     * [
42
     *     Post::class => [
43
     *         'id',
44
     *         'title',
45
     *         'createTime' => 'created_at',
46
     *         'length' => function ($post) {
47
     *             return strlen($post->content);
48
     *         },
49
     *     ],
50
     * ]
51
     * ```
52
     *
53
     * The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
54
     *
55
     * ```php
56
     * [
57
     *     'id' => 123,
58
     *     'title' => 'test',
59
     *     'createTime' => '2013-01-01 12:00AM',
60
     *     'length' => 301,
61
     * ]
62
     * ```
63
     *
64
     * @param array|object|string $object The object to be converted into an array.
65
     *
66
     * It is possible to provide default way of converting object to array for a specific class by implementing
67
     * {@see \Yiisoft\Arrays\ArrayableInterface} in its class.
68
     * @param array $properties A mapping from object class names to the properties that need to put into
69
     * the resulting arrays. The properties specified for each class is an array of the following format:
70
     *
71
     * - A field name to include as is.
72
     * - A key-value pair of desired array key name and model column name to take value from.
73
     * - A key-value pair of desired array key name and a callback which returns value.
74
     * @param bool $recursive Whether to recursively converts properties which are objects into arrays.
75
     *
76
     * @return array The array representation of the object.
77
     */
78 6
    public static function toArray($object, array $properties = [], bool $recursive = true): array
79
    {
80 6
        if (is_array($object)) {
81 5
            if ($recursive) {
82
                /** @var mixed $value */
83 4
                foreach ($object as $key => $value) {
84 4
                    if (is_array($value) || is_object($value)) {
85 4
                        $object[$key] = self::toArray($value, $properties);
86
                    }
87
                }
88
            }
89
90 5
            return $object;
91
        }
92
93 4
        if (is_object($object)) {
94 4
            if (!empty($properties)) {
95 1
                $className = get_class($object);
96 1
                if (!empty($properties[$className])) {
97 1
                    $result = [];
98
                    /**
99
                     * @var int|string $key
100
                     * @var string $name
101
                     */
102 1
                    foreach ($properties[$className] as $key => $name) {
103 1
                        if (is_int($key)) {
104
                            /** @var mixed */
105 1
                            $result[$name] = $object->$name;
106
                        } else {
107
                            /** @var mixed */
108 1
                            $result[$key] = self::getValue($object, $name);
109
                        }
110
                    }
111
112 1
                    return $recursive ? self::toArray($result, $properties) : $result;
113
                }
114
            }
115 4
            if ($object instanceof ArrayableInterface) {
116 3
                $result = $object->toArray([], [], $recursive);
117
            } else {
118 4
                $result = [];
119
                /**
120
                 * @var string $key
121
                 * @var mixed $value
122
                 */
123 4
                foreach ($object as $key => $value) {
124
                    /** @var mixed */
125 4
                    $result[$key] = $value;
126
                }
127
            }
128
129 4
            return $recursive ? self::toArray($result, $properties) : $result;
130
        }
131
132 1
        return [$object];
133
    }
134
135
    /**
136
     * Merges two or more arrays into one recursively.
137
     * If each array has an element with the same string key value, the latter
138
     * will overwrite the former (different from {@see array_merge_recursive()}).
139
     * Recursive merging will be conducted if both arrays have an element of array
140
     * type and are having the same key.
141
     * For integer-keyed elements, the elements from the latter array will
142
     * be appended to the former array.
143
     *
144
     * @param array ...$arrays Arrays to be merged.
145
     *
146
     * @return array The merged array (the original arrays are not changed).
147
     */
148 4
    public static function merge(...$arrays): array
149
    {
150 4
        $result = array_shift($arrays) ?: [];
151 4
        while (!empty($arrays)) {
152
            /** @var mixed $value */
153 3
            foreach (array_shift($arrays) as $key => $value) {
154 3
                if (is_int($key)) {
155 3
                    if (array_key_exists($key, $result)) {
156 3
                        if ($result[$key] !== $value) {
157
                            /** @var mixed */
158 3
                            $result[] = $value;
159
                        }
160
                    } else {
161
                        /** @var mixed */
162 3
                        $result[$key] = $value;
163
                    }
164 1
                } elseif (isset($result[$key]) && is_array($value) && is_array($result[$key])) {
165 1
                    $result[$key] = self::merge($result[$key], $value);
166
                } else {
167
                    /** @var mixed */
168 1
                    $result[$key] = $value;
169
                }
170
            }
171
        }
172 4
        return $result;
173
    }
174
175
    /**
176
     * Retrieves the value of an array element or object property with the given key or property name.
177
     * If the key does not exist in the array or object, the default value will be returned instead.
178
     *
179
     * Below are some usage examples,
180
     *
181
     * ```php
182
     * // Working with array:
183
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($_POST, 'username');
184
     *
185
     * // Working with object:
186
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($user, 'username');
187
     *
188
     * // Working with anonymous function:
189
     * $fullName = \Yiisoft\Arrays\ArrayHelper::getValue($user, function ($user, $defaultValue) {
190
     *     return $user->firstName . ' ' . $user->lastName;
191
     * });
192
     *
193
     * // Using an array of keys to retrieve the value:
194
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
195
     * ```
196
     *
197
     * @param array|object $array Array or object to extract value from.
198
     * @param array|Closure|float|int|string $key Key name of the array element,
199
     * an array of keys or property name of the object, or an anonymous function
200
     * returning the value. The anonymous function signature should be:
201
     * `function($array, $defaultValue)`.
202
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
203
     * getting value from an object.
204
     *
205
     * @psalm-param ArrayKey|Closure $key
206
     *
207
     * @return mixed The value of the element if found, default value otherwise.
208
     */
209 95
    public static function getValue($array, $key, $default = null)
210
    {
211 95
        if ($key instanceof Closure) {
212 16
            return $key($array, $default);
213
        }
214
215
        /** @psalm-suppress DocblockTypeContradiction */
216 87
        if (!is_array($array) && !is_object($array)) {
217 1
            throw new InvalidArgumentException(
218 1
                'getValue() can not get value from ' . gettype($array) . '. Only array and object are supported.'
219
            );
220
        }
221
222 86
        if (is_array($key)) {
223
            /** @psalm-var array<mixed,string|int> $key */
224 42
            $lastKey = array_pop($key);
225 42
            foreach ($key as $keyPart) {
226
                /** @var mixed */
227 39
                $array = self::getRootValue($array, $keyPart, null);
228 39
                if (!is_array($array) && !is_object($array)) {
229 10
                    return $default;
230
                }
231
            }
232 33
            return self::getRootValue($array, $lastKey, $default);
233
        }
234
235 46
        return self::getRootValue($array, $key, $default);
236
    }
237
238
    /**
239
     * @param mixed $array Array or object to extract value from, otherwise method will return $default.
240
     * @param float|int|string $key Key name of the array element or property name of the object.
241
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
242
     * getting value from an object.
243
     *
244
     * @return mixed The value of the element if found, default value otherwise.
245
     */
246 113
    private static function getRootValue($array, $key, $default)
247
    {
248 113
        if (is_array($array)) {
249 101
            $key = self::normalizeArrayKey($key);
250 101
            return array_key_exists($key, $array) ? $array[$key] : $default;
251
        }
252
253 14
        if (is_object($array)) {
254
            try {
255 14
                return $array::$$key;
256 14
            } catch (Throwable $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Throwable $e) 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...
257
                // This is expected to fail if the property does not exist, or __get() is not implemented.
258
                // It is not reliably possible to check whether a property is accessible beforehand.
259 14
                return $array->$key;
260
            }
261
        }
262
263
        return $default;
264
    }
265
266
    /**
267
     * Retrieves the value of an array element or object property with the given key or property name.
268
     * If the key does not exist in the array or object, the default value will be returned instead.
269
     *
270
     * The key may be specified in a dot-separated format to retrieve the value of a sub-array or the property
271
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
272
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
273
     * or `$array->x` is neither an array nor an object, the default value will be returned.
274
     * Note that if the array already has an element `x.y.z`, then its value will be returned
275
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
276
     * like `['x', 'y', 'z']`.
277
     *
278
     * Below are some usage examples,
279
     *
280
     * ```php
281
     * // Using separated format to retrieve the property of embedded object:
282
     * $street = \Yiisoft\Arrays\ArrayHelper::getValue($users, 'address.street');
283
     *
284
     * // Using an array of keys to retrieve the value:
285
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
286
     * ```
287
     *
288
     * @param array|object $array Array or object to extract value from.
289
     * @param array|Closure|float|int|string $path Key name of the array element, an array of keys or property name
290
     * of the object, or an anonymous function returning the value. The anonymous function signature should be:
291
     * `function($array, $defaultValue)`.
292
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
293
     * getting value from an object.
294
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
295
     * to "." (dot).
296
     *
297
     * @psalm-param ArrayPath|Closure $path
298
     *
299
     * @return mixed The value of the element if found, default value otherwise.
300
     */
301 37
    public static function getValueByPath($array, $path, $default = null, string $delimiter = '.')
302
    {
303 37
        return self::getValue(
304
            $array,
305 37
            $path instanceof Closure ? $path : self::parsePath($path, $delimiter),
306
            $default
307
        );
308
    }
309
310
    /**
311
     * Writes a value into an associative array at the key path specified.
312
     * If there is no such key path yet, it will be created recursively.
313
     * If the key exists, it will be overwritten.
314
     *
315
     * ```php
316
     *  $array = [
317
     *      'key' => [
318
     *          'in' => [
319
     *              'val1',
320
     *              'key' => 'val'
321
     *          ]
322
     *      ]
323
     *  ];
324
     * ```
325
     *
326
     * The result of `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
327
     * will be the following:
328
     *
329
     * ```php
330
     *  [
331
     *      'key' => [
332
     *          'in' => [
333
     *              'arr' => 'val'
334
     *          ]
335
     *      ]
336
     *  ]
337
     * ```
338
     *
339
     * @param array $array The array to write the value to.
340
     * @param array|float|int|string|null $key The path of where do you want to write a value to `$array`
341
     * the path can be described by an array of keys. If the path is null then `$array` will be assigned the `$value`.
342
     *
343
     * @psalm-param ArrayKey|null $key
344
     *
345
     * @param mixed $value The value to be written.
346
     */
347 29
    public static function setValue(array &$array, $key, $value): void
348
    {
349 29
        if ($key === null) {
350
            /** @var mixed */
351 2
            $array = $value;
352 2
            return;
353
        }
354
355 27
        $keys = is_array($key) ? $key : [$key];
356
357 27
        while (count($keys) > 1) {
358 15
            $k = self::normalizeArrayKey(array_shift($keys));
359 15
            if (!isset($array[$k])) {
360 8
                $array[$k] = [];
361
            }
362 15
            if (!is_array($array[$k])) {
363 2
                $array[$k] = [$array[$k]];
364
            }
365 15
            $array = &$array[$k];
366
        }
367
368
        /** @var mixed */
369 27
        $array[self::normalizeArrayKey(array_shift($keys))] = $value;
370
    }
371
372
    /**
373
     * Writes a value into an associative array at the key path specified.
374
     * If there is no such key path yet, it will be created recursively.
375
     * If the key exists, it will be overwritten.
376
     *
377
     * ```php
378
     *  $array = [
379
     *      'key' => [
380
     *          'in' => [
381
     *              'val1',
382
     *              'key' => 'val'
383
     *          ]
384
     *      ]
385
     *  ];
386
     * ```
387
     *
388
     * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
389
     *
390
     * ```php
391
     *  [
392
     *      'key' => [
393
     *          'in' => [
394
     *              ['arr' => 'val'],
395
     *              'key' => 'val'
396
     *          ]
397
     *      ]
398
     *  ]
399
     *
400
     * ```
401
     *
402
     * The result of
403
     * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
404
     * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
405
     * will be the following:
406
     *
407
     * ```php
408
     *  [
409
     *      'key' => [
410
     *          'in' => [
411
     *              'arr' => 'val'
412
     *          ]
413
     *      ]
414
     *  ]
415
     * ```
416
     *
417
     * @param array $array The array to write the value to.
418
     * @param array|float|int|string|null $path The path of where do you want to write a value to `$array`.
419
     * The path can be described by a string when each key should be separated by a dot.
420
     * You can also describe the path as an array of keys. If the path is null then `$array` will be assigned
421
     * the `$value`.
422
     * @param mixed $value The value to be written.
423
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
424
     * to "." (dot).
425
     *
426
     * @psalm-param ArrayPath|null $path
427
     */
428 21
    public static function setValueByPath(array &$array, $path, $value, string $delimiter = '.'): void
429
    {
430 21
        self::setValue($array, $path === null ? null : self::parsePath($path, $delimiter), $value);
431
    }
432
433
    /**
434
     * @param array|float|int|string $path The path of where do you want to write a value to `$array`.
435
     * The path can be described by a string when each key should be separated by delimiter. If a path item contains
436
     * delimiter, it can be escaped with "\" (backslash) or a custom delimiter can be used.
437
     * You can also describe the path as an array of keys.
438
     * @param string $delimiter A separator, used to parse string key for embedded object property retrieving. Defaults
439
     * to "." (dot).
440
     * @param bool $escapeDelimiter Whether to escape delimiter in the items of final array (in case of using string as
441
     * an input). When `false`, "\" (backslashes) are removed. For a "." as delimiter, "." becomes "\.". Defaults to
442
     * `false`.
443
     *
444
     * @psalm-param ArrayPath $path
445
     *
446
     * @return array|float|int|string
447
     * @psalm-return ArrayKey
448
     */
449 98
    public static function parsePath($path, string $delimiter = '.', bool $escapeDelimiter = false)
450
    {
451 98
        if (is_string($path)) {
452 93
            if (strlen($delimiter) !== 1) {
453 1
                throw new InvalidArgumentException('Only 1 character is allowed for delimiter.');
454
            }
455
456 92
            if (($path[0] ?? '') === $delimiter) {
457 1
                throw new InvalidArgumentException('Delimiter can\'t be at the very beginning.');
458
            }
459
460 91
            if (substr($path, -1) === $delimiter && substr($path, -2) !== '\\' . $delimiter) {
461 1
                throw new InvalidArgumentException('Delimiter can\'t be at the very end.');
462
            }
463
464 90
            $pattern = sprintf('/(?<!\\\\)\%s/', $delimiter);
465 90
            $matches =  preg_split($pattern, $path);
466
467 90
            if ($escapeDelimiter === true) {
468 1
                return $matches;
469
            }
470
471 89
            return array_map(static function (string $key) use ($delimiter): string {
472 89
                return str_replace('\\' . $delimiter, $delimiter, $key);
473
            }, $matches);
474
        }
475 22
        if (is_array($path)) {
476 17
            $newPath = [];
477 17
            foreach ($path as $key) {
478 17
                if (is_string($key) || is_array($key)) {
479
                    /** @var list<float|int|string> $parsedPath */
480 17
                    $parsedPath = self::parsePath($key, $delimiter);
481 17
                    $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

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