Passed
Pull Request — master (#94)
by Sergei
08:16
created

ArrayHelper::filter()   C

Complexity

Conditions 13
Paths 45

Size

Total Lines 55
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 31
CRAP Score 13

Importance

Changes 0
Metric Value
eloc 31
c 0
b 0
f 0
dl 0
loc 55
ccs 31
cts 31
cp 1
rs 6.6166
cc 13
nc 45
nop 2
crap 13

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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