Passed
Pull Request — master (#111)
by
unknown
01:59
created

ArrayHelper::parsePath()   B

Complexity

Conditions 11
Paths 9

Size

Total Lines 40
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 11.0086

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 24
c 1
b 0
f 0
dl 0
loc 40
ccs 23
cts 24
cp 0.9583
rs 7.3166
cc 11
nc 9
nop 3
crap 11.0086

How to fix   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 count;
14
use function get_class;
15
use function gettype;
16
use function in_array;
17
use function is_array;
18
use function is_float;
19
use function is_int;
20
use function is_object;
21
use function is_string;
22
use function preg_match_all;
23
use function sprintf;
24
use function str_replace;
25
use function strlen;
26
27
/**
28
 * Yii array helper provides static methods allowing you to deal with arrays more efficiently.
29
 *
30
 * @psalm-type ArrayKey = float|int|string|array<array-key,float|int|string>
31
 * @psalm-type ArrayPath = float|int|string|array<array-key,float|int|string|array<array-key,float|int|string>>
32
 */
33
final class ArrayHelper
34
{
35
    /**
36
     * Converts an object or an array of objects into an array.
37
     *
38
     * For example:
39
     *
40
     * ```php
41
     * [
42
     *     Post::class => [
43
     *         'id',
44
     *         'title',
45
     *         'createTime' => 'created_at',
46
     *         'length' => function ($post) {
47
     *             return strlen($post->content);
48
     *         },
49
     *     ],
50
     * ]
51
     * ```
52
     *
53
     * The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
54
     *
55
     * ```php
56
     * [
57
     *     'id' => 123,
58
     *     'title' => 'test',
59
     *     'createTime' => '2013-01-01 12:00AM',
60
     *     'length' => 301,
61
     * ]
62
     * ```
63
     *
64
     * @param array|object|string $object The object to be converted into an array.
65
     *
66
     * It is possible to provide default way of converting object to array for a specific class by implementing
67
     * {@see \Yiisoft\Arrays\ArrayableInterface} in its class.
68
     * @param array $properties A mapping from object class names to the properties that need to put into
69
     * the resulting arrays. The properties specified for each class is an array of the following format:
70
     *
71
     * - A field name to include as is.
72
     * - A key-value pair of desired array key name and model column name to take value from.
73
     * - A key-value pair of desired array key name and a callback which returns value.
74
     * @param bool $recursive Whether to recursively converts properties which are objects into arrays.
75
     *
76
     * @return array The array representation of the object.
77
     */
78 6
    public static function toArray($object, array $properties = [], bool $recursive = true): array
79
    {
80 6
        if (is_array($object)) {
81 5
            if ($recursive) {
82
                /** @var mixed $value */
83 4
                foreach ($object as $key => $value) {
84 4
                    if (is_array($value) || is_object($value)) {
85 4
                        $object[$key] = self::toArray($value, $properties);
86
                    }
87
                }
88
            }
89
90 5
            return $object;
91
        }
92
93 4
        if (is_object($object)) {
94 4
            if (!empty($properties)) {
95 1
                $className = get_class($object);
96 1
                if (!empty($properties[$className])) {
97 1
                    $result = [];
98
                    /**
99
                     * @var int|string $key
100
                     * @var string $name
101
                     */
102 1
                    foreach ($properties[$className] as $key => $name) {
103 1
                        if (is_int($key)) {
104
                            /** @var mixed */
105 1
                            $result[$name] = $object->$name;
106
                        } else {
107
                            /** @var mixed */
108 1
                            $result[$key] = self::getValue($object, $name);
109
                        }
110
                    }
111
112 1
                    return $recursive ? self::toArray($result, $properties) : $result;
113
                }
114
            }
115 4
            if ($object instanceof ArrayableInterface) {
116 3
                $result = $object->toArray([], [], $recursive);
117
            } else {
118 4
                $result = [];
119
                /**
120
                 * @var string $key
121
                 * @var mixed $value
122
                 */
123 4
                foreach ($object as $key => $value) {
124
                    /** @var mixed */
125 4
                    $result[$key] = $value;
126
                }
127
            }
128
129 4
            return $recursive ? self::toArray($result, $properties) : $result;
130
        }
131
132 1
        return [$object];
133
    }
134
135
    /**
136
     * Merges two or more arrays into one recursively.
137
     * If each array has an element with the same string key value, the latter
138
     * will overwrite the former (different from {@see array_merge_recursive()}).
139
     * Recursive merging will be conducted if both arrays have an element of array
140
     * type and are having the same key.
141
     * For integer-keyed elements, the elements from the latter array will
142
     * be appended to the former array.
143
     *
144
     * @param array ...$arrays Arrays to be merged.
145
     *
146
     * @return array The merged array (the original arrays are not changed).
147
     */
148 4
    public static function merge(...$arrays): array
149
    {
150 4
        $result = array_shift($arrays) ?: [];
151 4
        while (!empty($arrays)) {
152
            /** @var mixed $value */
153 3
            foreach (array_shift($arrays) as $key => $value) {
154 3
                if (is_int($key)) {
155 3
                    if (array_key_exists($key, $result)) {
156 3
                        if ($result[$key] !== $value) {
157
                            /** @var mixed */
158 3
                            $result[] = $value;
159
                        }
160
                    } else {
161
                        /** @var mixed */
162 3
                        $result[$key] = $value;
163
                    }
164 1
                } elseif (isset($result[$key]) && is_array($value) && is_array($result[$key])) {
165 1
                    $result[$key] = self::merge($result[$key], $value);
166
                } else {
167
                    /** @var mixed */
168 1
                    $result[$key] = $value;
169
                }
170
            }
171
        }
172 4
        return $result;
173
    }
174
175
    /**
176
     * Retrieves the value of an array element or object property with the given key or property name.
177
     * If the key does not exist in the array or object, the default value will be returned instead.
178
     *
179
     * Below are some usage examples,
180
     *
181
     * ```php
182
     * // Working with array:
183
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($_POST, 'username');
184
     *
185
     * // Working with object:
186
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($user, 'username');
187
     *
188
     * // Working with anonymous function:
189
     * $fullName = \Yiisoft\Arrays\ArrayHelper::getValue($user, function ($user, $defaultValue) {
190
     *     return $user->firstName . ' ' . $user->lastName;
191
     * });
192
     *
193
     * // Using an array of keys to retrieve the value:
194
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
195
     * ```
196
     *
197
     * @param array|object $array Array or object to extract value from.
198
     * @param array|Closure|float|int|string $key Key name of the array element,
199
     * an array of keys or property name of the object, or an anonymous function
200
     * returning the value. The anonymous function signature should be:
201
     * `function($array, $defaultValue)`.
202
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
203
     * getting value from an object.
204
     *
205
     * @psalm-param ArrayKey|Closure $key
206
     *
207
     * @return mixed The value of the element if found, default value otherwise.
208
     */
209 95
    public static function getValue($array, $key, $default = null)
210
    {
211 95
        if ($key instanceof Closure) {
212 16
            return $key($array, $default);
213
        }
214
215
        /** @psalm-suppress DocblockTypeContradiction */
216 87
        if (!is_array($array) && !is_object($array)) {
217 1
            throw new InvalidArgumentException(
218 1
                'getValue() can not get value from ' . gettype($array) . '. Only array and object are supported.'
219
            );
220
        }
221
222 86
        if (is_array($key)) {
223
            /** @psalm-var array<mixed,string|int> $key */
224 42
            $lastKey = array_pop($key);
225 42
            foreach ($key as $keyPart) {
226
                /** @var mixed */
227 39
                $array = self::getRootValue($array, $keyPart, null);
228 39
                if (!is_array($array) && !is_object($array)) {
229 10
                    return $default;
230
                }
231
            }
232 33
            return self::getRootValue($array, $lastKey, $default);
233
        }
234
235 46
        return self::getRootValue($array, $key, $default);
236
    }
237
238
    /**
239
     * @param mixed $array Array or object to extract value from, otherwise method will return $default.
240
     * @param float|int|string $key Key name of the array element or property name of the object.
241
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
242
     * getting value from an object.
243
     *
244
     * @return mixed The value of the element if found, default value otherwise.
245
     */
246 113
    private static function getRootValue($array, $key, $default)
247
    {
248 113
        if (is_array($array)) {
249 101
            $key = self::normalizeArrayKey($key);
250 101
            return array_key_exists($key, $array) ? $array[$key] : $default;
251
        }
252
253 14
        if (is_object($array)) {
254
            try {
255 14
                return $array::$$key;
256 14
            } catch (Throwable $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Throwable $e) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
257
                // This is expected to fail if the property does not exist, or __get() is not implemented.
258
                // It is not reliably possible to check whether a property is accessible beforehand.
259 14
                return $array->$key;
260
            }
261
        }
262
263
        return $default;
264
    }
265
266
    /**
267
     * Retrieves the value of an array element or object property with the given key or property name.
268
     * If the key does not exist in the array or object, the default value will be returned instead.
269
     *
270
     * The key may be specified in a dot-separated format to retrieve the value of a sub-array or the property
271
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
272
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
273
     * or `$array->x` is neither an array nor an object, the default value will be returned.
274
     * Note that if the array already has an element `x.y.z`, then its value will be returned
275
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
276
     * like `['x', 'y', 'z']`.
277
     *
278
     * Below are some usage examples,
279
     *
280
     * ```php
281
     * // Using separated format to retrieve the property of embedded object:
282
     * $street = \Yiisoft\Arrays\ArrayHelper::getValue($users, 'address.street');
283
     *
284
     * // Using an array of keys to retrieve the value:
285
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
286
     * ```
287
     *
288
     * @param array|object $array Array or object to extract value from.
289
     * @param array|Closure|float|int|string $path Key name of the array element, an array of keys or property name
290
     * of the object, or an anonymous function returning the value. The anonymous function signature should be:
291
     * `function($array, $defaultValue)`.
292
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
293
     * getting value from an object.
294
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
295
     * to "." (dot).
296
     *
297
     * @psalm-param ArrayPath|Closure $path
298
     *
299
     * @return mixed The value of the element if found, default value otherwise.
300
     */
301 37
    public static function getValueByPath($array, $path, $default = null, string $delimiter = '.')
302
    {
303 37
        return self::getValue(
304
            $array,
305 37
            $path instanceof Closure ? $path : self::parsePath($path, $delimiter),
306
            $default
307
        );
308
    }
309
310
    /**
311
     * Writes a value into an associative array at the key path specified.
312
     * If there is no such key path yet, it will be created recursively.
313
     * If the key exists, it will be overwritten.
314
     *
315
     * ```php
316
     *  $array = [
317
     *      'key' => [
318
     *          'in' => [
319
     *              'val1',
320
     *              'key' => 'val'
321
     *          ]
322
     *      ]
323
     *  ];
324
     * ```
325
     *
326
     * The result of `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
327
     * will be the following:
328
     *
329
     * ```php
330
     *  [
331
     *      'key' => [
332
     *          'in' => [
333
     *              'arr' => 'val'
334
     *          ]
335
     *      ]
336
     *  ]
337
     * ```
338
     *
339
     * @param array $array The array to write the value to.
340
     * @param array|float|int|string|null $key The path of where do you want to write a value to `$array`
341
     * the path can be described by an array of keys. If the path is null then `$array` will be assigned the `$value`.
342
     *
343
     * @psalm-param ArrayKey|null $key
344
     *
345
     * @param mixed $value The value to be written.
346
     */
347 29
    public static function setValue(array &$array, $key, $value): void
348
    {
349 29
        if ($key === null) {
350
            /** @var mixed */
351 2
            $array = $value;
352 2
            return;
353
        }
354
355 27
        $keys = is_array($key) ? $key : [$key];
356
357 27
        while (count($keys) > 1) {
358 15
            $k = self::normalizeArrayKey(array_shift($keys));
359 15
            if (!isset($array[$k])) {
360 8
                $array[$k] = [];
361
            }
362 15
            if (!is_array($array[$k])) {
363 2
                $array[$k] = [$array[$k]];
364
            }
365 15
            $array = &$array[$k];
366
        }
367
368
        /** @var mixed */
369 27
        $array[self::normalizeArrayKey(array_shift($keys))] = $value;
370
    }
371
372
    /**
373
     * Writes a value into an associative array at the key path specified.
374
     * If there is no such key path yet, it will be created recursively.
375
     * If the key exists, it will be overwritten.
376
     *
377
     * ```php
378
     *  $array = [
379
     *      'key' => [
380
     *          'in' => [
381
     *              'val1',
382
     *              'key' => 'val'
383
     *          ]
384
     *      ]
385
     *  ];
386
     * ```
387
     *
388
     * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
389
     *
390
     * ```php
391
     *  [
392
     *      'key' => [
393
     *          'in' => [
394
     *              ['arr' => 'val'],
395
     *              'key' => 'val'
396
     *          ]
397
     *      ]
398
     *  ]
399
     *
400
     * ```
401
     *
402
     * The result of
403
     * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
404
     * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
405
     * will be the following:
406
     *
407
     * ```php
408
     *  [
409
     *      'key' => [
410
     *          'in' => [
411
     *              'arr' => 'val'
412
     *          ]
413
     *      ]
414
     *  ]
415
     * ```
416
     *
417
     * @param array $array The array to write the value to.
418
     * @param array|float|int|string|null $path The path of where do you want to write a value to `$array`.
419
     * The path can be described by a string when each key should be separated by a dot.
420
     * You can also describe the path as an array of keys. If the path is null then `$array` will be assigned
421
     * the `$value`.
422
     * @param mixed $value The value to be written.
423
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
424
     * to "." (dot).
425
     *
426
     * @psalm-param ArrayPath|null $path
427
     */
428 21
    public static function setValueByPath(array &$array, $path, $value, string $delimiter = '.'): void
429
    {
430 21
        self::setValue($array, $path === null ? null : self::parsePath($path, $delimiter), $value);
431
    }
432
433
    /**
434
     * @param array|float|int|string $path The path of where do you want to write a value to `$array`.
435
     * The path can be described by a string when each key should be separated by delimiter. If a path item contains
436
     * delimiter, it can be escaped with "\" (backslash) or a custom delimiter can be used.
437
     * You can also describe the path as an array of keys.
438
     * @param string $delimiter A separator, used to parse string key for embedded object property retrieving. Defaults
439
     * to "." (dot).
440
     * @param bool $unescapeDelimiter Whether to unescape delimiter in the items of final array (in case pf using string
441
     * as an input) Defaults to `true`, meaning "\" (backslashes) are removed - "\." will become "." for "." delimiter.
442
     *
443
     * @psalm-param ArrayPath $path
444
     *
445
     * @return array|float|int|string
446
     * @psalm-return ArrayKey
447
     */
448 94
    public static function parsePath($path, string $delimiter = '.', bool $unescapeDelimiter = true)
449
    {
450 94
        if (is_string($path)) {
451 89
            if (strlen($delimiter) !== 1) {
452 1
                throw new InvalidArgumentException('Only 1 character is allowed for delimiter.');
453
            }
454
455 88
            if (($path[0] ?? '') === $delimiter) {
456 1
                throw new InvalidArgumentException('Delimiter can\'t be at the very beginning.');
457
            }
458
459 87
            if (substr($path, -1) === $delimiter && substr($path, -2) !== '\\' . $delimiter) {
460 1
                throw new InvalidArgumentException('Delimiter can\'t be at the very end.');
461
            }
462
463 86
            $pattern = sprintf('/(?:[^\%s\\\\]|\\\\.)+/', $delimiter);
464 86
            preg_match_all($pattern, $path, $matches);
465
466 86
            if ($unescapeDelimiter === false) {
467
                return $matches[0];
468
            }
469
470 86
            return array_map(static function (string $key) use ($delimiter): string {
471 86
                return str_replace('\\' . $delimiter, $delimiter, $key);
472 86
            }, $matches[0]);
473
        }
474 22
        if (is_array($path)) {
475 17
            $newPath = [];
476 17
            foreach ($path as $key) {
477 17
                if (is_string($key) || is_array($key)) {
478
                    /** @var list<float|int|string> $parsedPath */
479 17
                    $parsedPath = self::parsePath($key, $delimiter);
480 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

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