Passed
Push — master ( 073fcc...7af88e )
by Sergei
02:39
created

ArrayHelper   F

Complexity

Total Complexity 156

Size/Duplication

Total Lines 1342
Duplicated Lines 0 %

Test Coverage

Coverage 99.67%

Importance

Changes 12
Bugs 0 Features 0
Metric Value
wmc 156
eloc 297
c 12
b 0
f 0
dl 0
loc 1342
ccs 304
cts 305
cp 0.9967
rs 2

28 Methods

Rating   Name   Duplication   Size   Complexity  
C filter() 0 55 13
A getExistsKeys() 0 11 2
B isAssociative() 0 23 7
A setValue() 0 23 6
A pathExists() 0 7 1
A isIn() 0 14 6
A getObjectVars() 0 3 1
A getValueByPath() 0 6 2
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 toArray() 0 55 15
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
B getValue() 0 27 8
A setValueByPath() 0 3 2
A removeValue() 0 13 3
A normalizeArrayKey() 0 3 2
A isSubset() 0 10 3
B merge() 0 25 10
A getRootValue() 0 18 5
C parsePath() 0 77 13

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

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