Passed
Pull Request — master (#111)
by
unknown
13:45
created

ArrayHelper   F

Complexity

Total Complexity 150

Size/Duplication

Total Lines 1284
Duplicated Lines 0 %

Test Coverage

Coverage 99.65%

Importance

Changes 12
Bugs 0 Features 0
Metric Value
wmc 150
eloc 269
c 12
b 0
f 0
dl 0
loc 1284
ccs 282
cts 283
cp 0.9965
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
B parsePath() 0 25 7
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

How to fix   Complexity   

Complex Class

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

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

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

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

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