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

ArrayHelper   F

Complexity

Total Complexity 155

Size/Duplication

Total Lines 1305
Duplicated Lines 0 %

Test Coverage

Coverage 99.66%

Importance

Changes 15
Bugs 0 Features 0
Metric Value
wmc 155
eloc 280
c 15
b 0
f 0
dl 0
loc 1305
ccs 293
cts 294
cp 0.9966
rs 2

28 Methods

Rating   Name   Duplication   Size   Complexity  
A removeByPath() 0 3 1
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
C parsePath() 0 42 12
A keyExists() 0 19 6
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

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 103
    public static function parsePath($path, string $delimiter = '.', bool $escapeDelimiter = false)
450
    {
451 103
        if (is_string($path)) {
452 98
            if (strlen($delimiter) !== 1) {
453 1
                throw new InvalidArgumentException('Only 1 character is allowed for delimiter.');
454
            }
455
456 97
            if (($path[0] ?? '') === $delimiter) {
457 1
                throw new InvalidArgumentException('Delimiter can\'t be at the very beginning.');
458
            }
459
460 96
            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 95
            $pattern = ($delimiter !== '\\')
465 90
                ? sprintf('/(?:[^\%s\\\\]|\\\\.)+/', $delimiter)
466 5
                : '/(?:[^\\\\]|[\\\\]{2,}.)+/';
467 95
            preg_match_all($pattern, $path, $matches);
468
469 95
            if ($escapeDelimiter === true) {
470 1
                return $matches[0];
471
            }
472
473 94
            return array_map(static function (string $key) use ($delimiter): string {
474 94
                return str_replace('\\' . $delimiter, $delimiter, $key);
475 94
            }, $matches[0]);
476
        }
477 22
        if (is_array($path)) {
478 17
            $newPath = [];
479 17
            foreach ($path as $key) {
480 17
                if (is_string($key) || is_array($key)) {
481
                    /** @var list<float|int|string> $parsedPath */
482 17
                    $parsedPath = self::parsePath($key, $delimiter);
483 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

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