Passed
Pull Request — master (#82)
by Sergei
02:07
created

ArrayHelper   F

Complexity

Total Complexity 139

Size/Duplication

Total Lines 1205
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 11
Bugs 0 Features 0
Metric Value
wmc 139
eloc 252
c 11
b 0
f 0
dl 0
loc 1205
ccs 271
cts 271
cp 1
rs 2

27 Methods

Rating   Name   Duplication   Size   Complexity  
B filter() 0 52 11
B isAssociative() 0 25 7
A getExistsKeys() 0 11 2
A setValue() 0 23 6
A pathExists() 0 7 1
A isIn() 0 14 6
A getObjectVars() 0 3 1
A getValueByPath() 0 3 1
A isIndexed() 0 18 5
B index() 0 38 9
A htmlDecode() 0 19 6
A remove() 0 21 6
A parsePath() 0 17 6
C toArray() 0 55 15
A keyExists() 0 19 6
A removeByPath() 0 3 1
A getColumn() 0 16 4
A rootKeyExists() 0 15 4
A htmlEncode() 0 21 6
A map() 0 24 6
A getValue() 0 24 6
A setValueByPath() 0 3 1
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 get_class;
13
use function in_array;
14
use function is_array;
15
use function is_float;
16
use function is_int;
17
use function is_object;
18
use function is_string;
19
20
/**
21
 * Yii array helper provides static methods allowing you to deal with arrays more efficiently.
22
 */
23
class ArrayHelper
24
{
25
    /**
26
     * Converts an object or an array of objects into an array.
27
     *
28
     * For example:
29
     *
30
     * ```php
31
     * [
32
     *     Post::class => [
33
     *         'id',
34
     *         'title',
35
     *         'createTime' => 'created_at',
36
     *         'length' => function ($post) {
37
     *             return strlen($post->content);
38
     *         },
39
     *     ],
40
     * ]
41
     * ```
42
     *
43
     * The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
44
     *
45
     * ```php
46
     * [
47
     *     'id' => 123,
48
     *     'title' => 'test',
49
     *     'createTime' => '2013-01-01 12:00AM',
50
     *     'length' => 301,
51
     * ]
52
     * ```
53
     *
54
     * @param array|object|string $object the object to be converted into an array.
55
     *
56
     * It is possible to provide default way of converting object to array for a specific class by implementing
57
     * `Yiisoft\Arrays\ArrayableInterface` interface in that class.
58
     * @param array $properties a mapping from object class names to the properties that need to put into the resulting arrays.
59
     * The properties specified for each class is an array of the following format:
60
     *
61
     * - A field name to include as is.
62
     * - A key-value pair of desired array key name and model column name to take value from.
63
     * - A key-value pair of desired array key name and a callback which returns value.
64
     * @param bool $recursive whether to recursively converts properties which are objects into arrays.
65
     *
66
     * @return array the array representation of the object
67
     */
68 6
    public static function toArray($object, array $properties = [], bool $recursive = true): array
69
    {
70 6
        if (is_array($object)) {
71 5
            if ($recursive) {
72
                /** @var mixed $value */
73 4
                foreach ($object as $key => $value) {
74 4
                    if (is_array($value) || is_object($value)) {
75 4
                        $object[$key] = static::toArray($value, $properties);
76
                    }
77
                }
78
            }
79
80 5
            return $object;
81
        }
82
83 4
        if (is_object($object)) {
84 4
            if (!empty($properties)) {
85 1
                $className = get_class($object);
86 1
                if (!empty($properties[$className])) {
87 1
                    $result = [];
88
                    /**
89
                     * @var int|string $key
90
                     * @var string $name
91
                     */
92 1
                    foreach ($properties[$className] as $key => $name) {
93 1
                        if (is_int($key)) {
94
                            /** @var mixed */
95 1
                            $result[$name] = $object->$name;
96
                        } else {
97
                            /** @var mixed */
98 1
                            $result[$key] = static::getValue($object, $name);
99
                        }
100
                    }
101
102 1
                    return $recursive ? static::toArray($result, $properties) : $result;
103
                }
104
            }
105 4
            if ($object instanceof ArrayableInterface) {
106 3
                $result = $object->toArray([], [], $recursive);
107
            } else {
108 4
                $result = [];
109
                /**
110
                 * @var string $key
111
                 * @var mixed $value
112
                 */
113 4
                foreach ($object as $key => $value) {
114
                    /** @var mixed */
115 4
                    $result[$key] = $value;
116
                }
117
            }
118
119 4
            return $recursive ? static::toArray($result, $properties) : $result;
120
        }
121
122 1
        return [$object];
123
    }
124
125
    /**
126
     * Merges two or more arrays into one recursively.
127
     * If each array has an element with the same string key value, the latter
128
     * will overwrite the former (different from `array_merge_recursive`).
129
     * Recursive merging will be conducted if both arrays have an element of array
130
     * type and are having the same key.
131
     * For integer-keyed elements, the elements from the latter array will
132
     * be appended to the former array.
133
     *
134
     * @param array ...$arrays arrays to be merged
135
     *
136
     * @return array the merged array (the original arrays are not changed)
137
     */
138 4
    public static function merge(...$arrays): array
139
    {
140 4
        $result = array_shift($arrays) ?: [];
141 4
        while (!empty($arrays)) {
142
            /** @var mixed $value */
143 3
            foreach (array_shift($arrays) as $key => $value) {
144 3
                if (is_int($key)) {
145 3
                    if (array_key_exists($key, $result)) {
146 3
                        if ($result[$key] !== $value) {
147
                            /** @var mixed */
148 3
                            $result[] = $value;
149
                        }
150
                    } else {
151
                        /** @var mixed */
152 3
                        $result[$key] = $value;
153
                    }
154 1
                } elseif (isset($result[$key]) && is_array($value) && is_array($result[$key])) {
155 1
                    $result[$key] = self::merge($result[$key], $value);
156
                } else {
157
                    /** @var mixed */
158 1
                    $result[$key] = $value;
159
                }
160
            }
161
        }
162 4
        return $result;
163
    }
164
165
    /**
166
     * Retrieves the value of an array element or object property with the given key or property name.
167
     * If the key does not exist in the array or object, the default value will be returned instead.
168
     *
169
     * Below are some usage examples,
170
     *
171
     * ```php
172
     * // working with array
173
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($_POST, 'username');
174
     * // working with object
175
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($user, 'username');
176
     * // working with anonymous function
177
     * $fullName = \Yiisoft\Arrays\ArrayHelper::getValue($user, function ($user, $defaultValue) {
178
     *     return $user->firstName . ' ' . $user->lastName;
179
     * });
180
     * // using an array of keys to retrieve the value
181
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
182
     * ```
183
     *
184
     * @param array|object $array array or object to extract value from
185
     * @param array|Closure|float|int|string $key key name of the array element,
186
     * an array of keys or property name of the object, or an anonymous function
187
     * returning the value. The anonymous function signature should be:
188
     * `function($array, $defaultValue)`.
189
     * @param mixed $default the default value to be returned if the specified array key does not exist. Not used when
190
     * getting value from an object.
191
     *
192
     * @return mixed the value of the element if found, default value otherwise
193
     */
194 68
    public static function getValue($array, $key, $default = null)
195
    {
196 68
        if ($key instanceof Closure) {
197 10
            return $key($array, $default);
198
        }
199
200
        /** @psalm-suppress DocblockTypeContradiction */
201 65
        if (!is_array($array) && !is_object($array)) {
202 1
            throw new InvalidArgumentException(
203 1
                'getValue() can not get value from ' . gettype($array) . '. Only array and object are supported.'
204
            );
205
        }
206
207 64
        if (is_array($key)) {
208
            /** @psalm-var array<mixed,string|int> $key */
209 37
            $lastKey = array_pop($key);
210 37
            foreach ($key as $keyPart) {
211
                /** @var mixed */
212 34
                $array = static::getRootValue($array, $keyPart, $default);
213
            }
214 37
            return static::getRootValue($array, $lastKey, $default);
215
        }
216
217 29
        return static::getRootValue($array, $key, $default);
218
    }
219
220
    /**
221
     * @param mixed $array array or object to extract value from, otherwise method will return $default
222
     * @param float|int|string $key key name of the array element or property name of the object,
223
     * @param mixed $default the default value to be returned if the specified array key does not exist. Not used when
224
     * getting value from an object.
225
     *
226
     * @return mixed the value of the element if found, default value otherwise
227
     */
228 91
    private static function getRootValue($array, $key, $default)
229
    {
230 91
        if (is_array($array)) {
231 79
            $key = static::normalizeArrayKey($key);
232 79
            return array_key_exists($key, $array) ? $array[$key] : $default;
233
        }
234
235 22
        if (is_object($array)) {
236
            try {
237 14
                return $array::$$key;
238 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...
239
                // this is expected to fail if the property does not exist, or __get() is not implemented
240
                // it is not reliably possible to check whether a property is accessible beforehand
241 14
                return $array->$key;
242
            }
243
        }
244
245 8
        return $default;
246
    }
247
248
    /**
249
     * Retrieves the value of an array element or object property with the given key or property name.
250
     * If the key does not exist in the array or object, the default value will be returned instead.
251
     *
252
     * The key may be specified in a dot-separated format to retrieve the value of a sub-array or the property
253
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
254
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
255
     * or `$array->x` is neither an array nor an object, the default value will be returned.
256
     * Note that if the array already has an element `x.y.z`, then its value will be returned
257
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
258
     * like `['x', 'y', 'z']`.
259
     *
260
     * Below are some usage examples,
261
     *
262
     * ```php
263
     * // using separated format to retrieve the property of embedded object
264
     * $street = \Yiisoft\Arrays\ArrayHelper::getValue($users, 'address.street');
265
     * // using an array of keys to retrieve the value
266
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
267
     * ```
268
     *
269
     * @param array|object $array array or object to extract value from
270
     * @param array|Closure|float|int|string $path key name of the array element, an array of keys or property name
271
     * of the object, or an anonymous function returning the value. The anonymous function signature should be:
272
     * `function($array, $defaultValue)`.
273
     * @param mixed $default the default value to be returned if the specified array key does not exist. Not used when
274
     * getting value from an object.
275
     * @param string $delimiter a separator, used to parse string $key for embedded object property retrieving. Defaults
276
     * to "." (dot).
277
     *
278
     * @return mixed the value of the element if found, default value otherwise
279
     */
280 33
    public static function getValueByPath($array, $path, $default = null, string $delimiter = '.')
281
    {
282 33
        return static::getValue($array, static::parsePath($path, $delimiter), $default);
283
    }
284
285
    /**
286
     * Writes a value into an associative array at the key path specified.
287
     * If there is no such key path yet, it will be created recursively.
288
     * If the key exists, it will be overwritten.
289
     *
290
     * ```php
291
     *  $array = [
292
     *      'key' => [
293
     *          'in' => [
294
     *              'val1',
295
     *              'key' => 'val'
296
     *          ]
297
     *      ]
298
     *  ];
299
     * ```
300
     *
301
     * The result of `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
302
     * will be the following:
303
     *
304
     * ```php
305
     *  [
306
     *      'key' => [
307
     *          'in' => [
308
     *              'arr' => 'val'
309
     *          ]
310
     *      ]
311
     *  ]
312
     * ```
313
     *
314
     * @param array $array the array to write the value to
315
     * @param array|float|int|string|null $key the path of where do you want to write a value to `$array`
316
     * the path can be described by an array of keys
317
     * if the path is null then `$array` will be assigned the `$value`
318
     * @psalm-param array<mixed, string|int|float>|float|int|string|null $key
319
     *
320
     * @param mixed $value the value to be written
321
     */
322 29
    public static function setValue(array &$array, $key, $value): void
323
    {
324 29
        if ($key === null) {
325
            /** @var mixed */
326 2
            $array = $value;
327 2
            return;
328
        }
329
330 27
        $keys = is_array($key) ? $key : [$key];
331
332 27
        while (count($keys) > 1) {
333 15
            $k = static::normalizeArrayKey(array_shift($keys));
334 15
            if (!isset($array[$k])) {
335 8
                $array[$k] = [];
336
            }
337 15
            if (!is_array($array[$k])) {
338 2
                $array[$k] = [$array[$k]];
339
            }
340 15
            $array = &$array[$k];
341
        }
342
343
        /** @var mixed */
344 27
        $array[static::normalizeArrayKey(array_shift($keys))] = $value;
345 27
    }
346
347
    /**
348
     * Writes a value into an associative array at the key path specified.
349
     * If there is no such key path yet, it will be created recursively.
350
     * If the key exists, it will be overwritten.
351
     *
352
     * ```php
353
     *  $array = [
354
     *      'key' => [
355
     *          'in' => [
356
     *              'val1',
357
     *              'key' => 'val'
358
     *          ]
359
     *      ]
360
     *  ];
361
     * ```
362
     *
363
     * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
364
     *
365
     * ```php
366
     *  [
367
     *      'key' => [
368
     *          'in' => [
369
     *              ['arr' => 'val'],
370
     *              'key' => 'val'
371
     *          ]
372
     *      ]
373
     *  ]
374
     *
375
     * ```
376
     *
377
     * The result of
378
     * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
379
     * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
380
     * will be the following:
381
     *
382
     * ```php
383
     *  [
384
     *      'key' => [
385
     *          'in' => [
386
     *              'arr' => 'val'
387
     *          ]
388
     *      ]
389
     *  ]
390
     * ```
391
     *
392
     * @param array $array the array to write the value to
393
     * @param array|float|int|string|null $path the path of where do you want to write a value to `$array`
394
     * the path can be described by a string when each key should be separated by a dot
395
     * you can also describe the path as an array of keys
396
     * if the path is null then `$array` will be assigned the `$value`
397
     * @param mixed $value the value to be written
398
     * @param string $delimiter
399
     */
400 21
    public static function setValueByPath(array &$array, $path, $value, string $delimiter = '.'): void
401
    {
402 21
        static::setValue($array, static::parsePath($path, $delimiter), $value);
403 21
    }
404
405
    /**
406
     * @param mixed $path
407
     * @param string $delimiter
408
     *
409
     * @return mixed
410
     */
411 84
    private static function parsePath($path, string $delimiter)
412
    {
413 84
        if (is_string($path)) {
414 77
            return explode($delimiter, $path);
415
        }
416 24
        if (is_array($path)) {
417 17
            $newPath = [];
418 17
            foreach ($path as $key) {
419 17
                if (is_string($key) || is_array($key)) {
420 17
                    $newPath = array_merge($newPath, static::parsePath($key, $delimiter));
421
                } else {
422 4
                    $newPath[] = $key;
423
                }
424
            }
425 17
            return $newPath;
426
        }
427 7
        return $path;
428
    }
429
430
    /**
431
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
432
     * will be returned instead.
433
     *
434
     * Usage examples,
435
     *
436
     * ```php
437
     * // $array = ['type' => 'A', 'options' => [1, 2]];
438
     * // working with array
439
     * $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
440
     * // $array content
441
     * // $array = ['options' => [1, 2]];
442
     * ```
443
     *
444
     * @param array $array the array to extract value from
445
     * @param array|float|int|string $key key name of the array element or associative array at the key path specified
446
     * @psalm-param array<mixed, float|int|string>|float|int|string $key
447
     *
448
     * @param mixed $default the default value to be returned if the specified key does not exist
449
     *
450
     * @return mixed the value of the element if found, default value otherwise
451
     */
452 13
    public static function remove(array &$array, $key, $default = null)
453
    {
454 13
        $keys = is_array($key) ? $key : [$key];
455
456 13
        while (count($keys) > 1) {
457 7
            $key = static::normalizeArrayKey(array_shift($keys));
458 7
            if (!isset($array[$key]) || !is_array($array[$key])) {
459 1
                return $default;
460
            }
461 6
            $array = &$array[$key];
462
        }
463
464 12
        $key = static::normalizeArrayKey(array_shift($keys));
465 12
        if (array_key_exists($key, $array)) {
466
            /** @var mixed */
467 11
            $value = $array[$key];
468 11
            unset($array[$key]);
469 11
            return $value;
470
        }
471
472 1
        return $default;
473
    }
474
475
    /**
476
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
477
     * will be returned instead.
478
     *
479
     * Usage examples,
480
     *
481
     * ```php
482
     * // $array = ['type' => 'A', 'options' => [1, 2]];
483
     * // working with array
484
     * $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
485
     * // $array content
486
     * // $array = ['options' => [1, 2]];
487
     * ```
488
     *
489
     * @param array $array the array to extract value from
490
     * @param array|string $path key name of the array element or associative array at the key path specified
491
     * the path can be described by a string when each key should be separated by a delimiter (default is dot)
492
     * @param mixed $default the default value to be returned if the specified key does not exist
493
     * @param string $delimiter
494
     *
495
     * @return mixed the value of the element if found, default value otherwise
496
     */
497 5
    public static function removeByPath(array &$array, $path, $default = null, string $delimiter = '.')
498
    {
499 5
        return static::remove($array, static::parsePath($path, $delimiter), $default);
500
    }
501
502
    /**
503
     * Removes items with matching values from the array and returns the removed items.
504
     *
505
     * Example,
506
     *
507
     * ```php
508
     * $array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
509
     * $removed = \Yiisoft\Arrays\ArrayHelper::removeValue($array, 'Jackson');
510
     * // result:
511
     * // $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
512
     * // $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
513
     * ```
514
     *
515
     * @param array $array the array where to look the value from
516
     * @param mixed $value the value to remove from the array
517
     *
518
     * @return array the items that were removed from the array
519
     */
520 2
    public static function removeValue(array &$array, $value): array
521
    {
522 2
        $result = [];
523
        /** @psalm-var mixed $val */
524 2
        foreach ($array as $key => $val) {
525 2
            if ($val === $value) {
526
                /** @var mixed */
527 1
                $result[$key] = $val;
528 1
                unset($array[$key]);
529
            }
530
        }
531
532 2
        return $result;
533
    }
534
535
    /**
536
     * Indexes and/or groups the array according to a specified key.
537
     * The input should be either multidimensional array or an array of objects.
538
     *
539
     * The $key can be either a key name of the sub-array, a property name of object, or an anonymous
540
     * function that must return the value that will be used as a key.
541
     *
542
     * $groups is an array of keys, that will be used to group the input array into one or more sub-arrays based
543
     * on keys specified.
544
     *
545
     * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
546
     * to `$groups` not specified then the element is discarded.
547
     *
548
     * For example:
549
     *
550
     * ```php
551
     * $array = [
552
     *     ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
553
     *     ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
554
     *     ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
555
     * ];
556
     * $result = ArrayHelper::index($array, 'id');
557
     * ```
558
     *
559
     * The result will be an associative array, where the key is the value of `id` attribute
560
     *
561
     * ```php
562
     * [
563
     *     '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
564
     *     '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
565
     *     // The second element of an original array is overwritten by the last element because of the same id
566
     * ]
567
     * ```
568
     *
569
     * An anonymous function can be used in the grouping array as well.
570
     *
571
     * ```php
572
     * $result = ArrayHelper::index($array, function ($element) {
573
     *     return $element['id'];
574
     * });
575
     * ```
576
     *
577
     * Passing `id` as a third argument will group `$array` by `id`:
578
     *
579
     * ```php
580
     * $result = ArrayHelper::index($array, null, 'id');
581
     * ```
582
     *
583
     * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
584
     * and indexed by `data` on the third level:
585
     *
586
     * ```php
587
     * [
588
     *     '123' => [
589
     *         ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
590
     *     ],
591
     *     '345' => [ // all elements with this index are present in the result array
592
     *         ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
593
     *         ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
594
     *     ]
595
     * ]
596
     * ```
597
     *
598
     * The anonymous function can be used in the array of grouping keys as well:
599
     *
600
     * ```php
601
     * $result = ArrayHelper::index($array, 'data', [function ($element) {
602
     *     return $element['id'];
603
     * }, 'device']);
604
     * ```
605
     *
606
     * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
607
     * and indexed by the `data` on the third level:
608
     *
609
     * ```php
610
     * [
611
     *     '123' => [
612
     *         'laptop' => [
613
     *             'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
614
     *         ]
615
     *     ],
616
     *     '345' => [
617
     *         'tablet' => [
618
     *             'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
619
     *         ],
620
     *         'smartphone' => [
621
     *             'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
622
     *         ]
623
     *     ]
624
     * ]
625
     * ```
626
     *
627
     * @param array $array the array that needs to be indexed or grouped
628
     * @psalm-param array<mixed, array|object> $array
629
     *
630
     * @param Closure|string|null $key the column name or anonymous function which result will be used to index the array
631
     * @param Closure[]|string|string[]|null $groups the array of keys, that will be used to group the input array
632
     * by one or more keys. If the $key attribute or its value for the particular element is null and $groups is not
633
     * defined, the array element will be discarded. Otherwise, if $groups is specified, array element will be added
634
     * to the result array without any key.
635
     *
636
     * @return array the indexed and/or grouped array
637
     */
638 7
    public static function index(array $array, $key, $groups = []): array
639
    {
640 7
        $result = [];
641 7
        $groups = (array)$groups;
642
643 7
        foreach ($array as $element) {
644
            /** @psalm-suppress DocblockTypeContradiction */
645 7
            if (!is_array($element) && !is_object($element)) {
646 4
                throw new InvalidArgumentException(
647 4
                    'index() can not get value from ' . gettype($element)
648 4
                    . '. The $array should be either multidimensional array or an array of objects.'
649
                );
650
            }
651
652 5
            $lastArray = &$result;
653
654 5
            foreach ($groups as $group) {
655 1
                $value = static::getValue($element, $group);
656 1
                if (!array_key_exists($value, $lastArray)) {
657 1
                    $lastArray[$value] = [];
658
                }
659 1
                $lastArray = &$lastArray[$value];
660
            }
661
662 5
            if ($key === null) {
663 3
                if (!empty($groups)) {
664 3
                    $lastArray[] = $element;
665
                }
666
            } else {
667 4
                $value = static::getValue($element, $key);
668 4
                if ($value !== null) {
669 4
                    $lastArray[static::normalizeArrayKey($value)] = $element;
670
                }
671
            }
672 5
            unset($lastArray);
673
        }
674
675 3
        return $result;
676
    }
677
678
    /**
679
     * Returns the values of a specified column in an array.
680
     * The input array should be multidimensional or an array of objects.
681
     *
682
     * For example,
683
     *
684
     * ```php
685
     * $array = [
686
     *     ['id' => '123', 'data' => 'abc'],
687
     *     ['id' => '345', 'data' => 'def'],
688
     * ];
689
     * $result = ArrayHelper::getColumn($array, 'id');
690
     * // the result is: ['123', '345']
691
     *
692
     * // using anonymous function
693
     * $result = ArrayHelper::getColumn($array, function ($element) {
694
     *     return $element['id'];
695
     * });
696
     * ```
697
     *
698
     * @param array $array
699
     * @psalm-param array<mixed, array|object> $array
700
     *
701
     * @param Closure|string $name
702
     * @param bool $keepKeys whether to maintain the array keys. If false, the resulting array
703
     * will be re-indexed with integers.
704
     *
705
     * @return array the list of column values
706
     */
707 5
    public static function getColumn(array $array, $name, bool $keepKeys = true): array
708
    {
709 5
        $result = [];
710 5
        if ($keepKeys) {
711 5
            foreach ($array as $k => $element) {
712
                /** @var mixed */
713 5
                $result[$k] = static::getValue($element, $name);
714
            }
715
        } else {
716 1
            foreach ($array as $element) {
717
                /** @var mixed */
718 1
                $result[] = static::getValue($element, $name);
719
            }
720
        }
721
722 5
        return $result;
723
    }
724
725
    /**
726
     * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
727
     * The `$from` and `$to` parameters specify the key names or property names to set up the map.
728
     * Optionally, one can further group the map according to a grouping field `$group`.
729
     *
730
     * For example,
731
     *
732
     * ```php
733
     * $array = [
734
     *     ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
735
     *     ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
736
     *     ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
737
     * ];
738
     *
739
     * $result = ArrayHelper::map($array, 'id', 'name');
740
     * // the result is:
741
     * // [
742
     * //     '123' => 'aaa',
743
     * //     '124' => 'bbb',
744
     * //     '345' => 'ccc',
745
     * // ]
746
     *
747
     * $result = ArrayHelper::map($array, 'id', 'name', 'class');
748
     * // the result is:
749
     * // [
750
     * //     'x' => [
751
     * //         '123' => 'aaa',
752
     * //         '124' => 'bbb',
753
     * //     ],
754
     * //     'y' => [
755
     * //         '345' => 'ccc',
756
     * //     ],
757
     * // ]
758
     * ```
759
     *
760
     * @param array $array
761
     * @psalm-param array<mixed, array|object> $array
762
     *
763
     * @param Closure|string $from
764
     * @param Closure|string $to
765
     * @param Closure|string|null $group
766
     *
767
     * @return array
768
     */
769 3
    public static function map(array $array, $from, $to, $group = null): array
770
    {
771 3
        if ($group === null) {
772 2
            if ($from instanceof Closure || $to instanceof Closure) {
773 1
                $result = [];
774 1
                foreach ($array as $element) {
775
                    /** @var mixed */
776 1
                    $result[static::getValue($element, $from)] = static::getValue($element, $to);
777
                }
778
779 1
                return $result;
780
            }
781
782 2
            return array_column($array, $to, $from);
783
        }
784
785 2
        $result = [];
786 2
        foreach ($array as $element) {
787 2
            $key = static::getValue($element, $from);
788
            /** @var mixed */
789 2
            $result[static::getValue($element, $group)][$key] = static::getValue($element, $to);
790
        }
791
792 2
        return $result;
793
    }
794
795
    /**
796
     * Checks if the given array contains the specified key.
797
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
798
     * key comparison.
799
     *
800
     * @param array $array the array with keys to check
801
     * @param array|float|int|string $key the key to check
802
     * @param bool $caseSensitive whether the key comparison should be case-sensitive
803
     *
804
     * @return bool whether the array contains the specified key
805
     */
806 41
    public static function keyExists(array $array, $key, bool $caseSensitive = true): bool
807
    {
808 41
        if (is_array($key)) {
809 31
            if (count($key) === 1) {
810 25
                return static::rootKeyExists($array, end($key), $caseSensitive);
811
            }
812
813 27
            foreach (self::getExistsKeys($array, array_shift($key), $caseSensitive) as $existKey) {
814
                /** @var mixed */
815 27
                $array = static::getRootValue($array, $existKey, null);
816 27
                if (is_array($array) && self::keyExists($array, $key, $caseSensitive)) {
817 14
                    return true;
818
                }
819
            }
820
821 13
            return false;
822
        }
823
824 10
        return static::rootKeyExists($array, $key, $caseSensitive);
825
    }
826
827
    /**
828
     * @param array $array
829
     * @param float|int|string $key
830
     * @param bool $caseSensitive
831
     *
832
     * @return bool
833
     */
834 35
    private static function rootKeyExists(array $array, $key, bool $caseSensitive): bool
835
    {
836 35
        $key = (string)$key;
837
838 35
        if ($caseSensitive) {
839 29
            return array_key_exists($key, $array);
840
        }
841
842 6
        foreach (array_keys($array) as $k) {
843 6
            if (strcasecmp($key, (string)$k) === 0) {
844 5
                return true;
845
            }
846
        }
847
848 1
        return false;
849
    }
850
851
    /**
852
     * @param array $array
853
     * @param float|int|string $key
854
     * @param bool $caseSensitive
855
     *
856
     * @return array
857
     */
858 27
    private static function getExistsKeys(array $array, $key, bool $caseSensitive): array
859
    {
860 27
        $key = (string)$key;
861
862 27
        if ($caseSensitive) {
863 22
            return [$key];
864
        }
865
866 5
        return array_filter(
867 5
            array_keys($array),
868 5
            fn ($k) => strcasecmp($key, (string)$k) === 0
869 5
        );
870
    }
871
872
    /**
873
     * Checks if the given array contains the specified key. The key may be specified in a dot format.
874
     * In particular, if the key is `x.y.z`, then key would be `$array['x']['y']['z']`.
875
     *
876
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
877
     * key comparison.
878
     *
879
     * @param array $array
880
     * @param array|float|int|string $path
881
     * @param bool $caseSensitive
882
     * @param string $delimiter
883
     *
884
     * @return bool
885
     */
886 26
    public static function pathExists(
887
        array $array,
888
        $path,
889
        bool $caseSensitive = true,
890
        string $delimiter = '.'
891
    ): bool {
892 26
        return static::keyExists($array, static::parsePath($path, $delimiter), $caseSensitive);
893
    }
894
895
    /**
896
     * Encodes special characters in an array of strings into HTML entities.
897
     * Only array values will be encoded by default.
898
     * If a value is an array, this method will also encode it recursively.
899
     * Only string values will be encoded.
900
     *
901
     * @param array $data data to be encoded
902
     * @psalm-param array<mixed, mixed> $data
903
     *
904
     * @param bool $valuesOnly whether to encode array values only. If false,
905
     * both the array keys and array values will be encoded.
906
     * @param string|null $encoding The encoding to use, defaults to `ini_get('default_charset')`.
907
     *
908
     * @return array the encoded data
909
     *
910
     * @see https://www.php.net/manual/en/function.htmlspecialchars.php
911
     */
912 1
    public static function htmlEncode(array $data, bool $valuesOnly = true, string $encoding = null): array
913
    {
914 1
        $d = [];
915
        /** @var mixed $value */
916 1
        foreach ($data as $key => $value) {
917 1
            if (!$valuesOnly && is_string($key)) {
918
                /** @psalm-suppress PossiblyNullArgument */
919 1
                $key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $encoding, true);
920
            }
921 1
            if (is_string($value)) {
922
                /** @psalm-suppress PossiblyNullArgument */
923 1
                $d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $encoding, true);
924 1
            } elseif (is_array($value)) {
925 1
                $d[$key] = static::htmlEncode($value, $valuesOnly, $encoding);
926
            } else {
927
                /** @var mixed */
928 1
                $d[$key] = $value;
929
            }
930
        }
931
932 1
        return $d;
933
    }
934
935
    /**
936
     * Decodes HTML entities into the corresponding characters in an array of strings.
937
     * Only array values will be decoded by default.
938
     * If a value is an array, this method will also decode it recursively.
939
     * Only string values will be decoded.
940
     *
941
     * @param array $data data to be decoded
942
     * @psalm-param array<mixed, mixed> $data
943
     *
944
     * @param bool $valuesOnly whether to decode array values only. If false,
945
     * both the array keys and array values will be decoded.
946
     *
947
     * @return array the decoded data
948
     *
949
     * @see https://www.php.net/manual/en/function.htmlspecialchars-decode.php
950
     */
951 1
    public static function htmlDecode(array $data, bool $valuesOnly = true): array
952
    {
953 1
        $d = [];
954
        /** @psalm-var mixed $value */
955 1
        foreach ($data as $key => $value) {
956 1
            if (!$valuesOnly && is_string($key)) {
957 1
                $key = htmlspecialchars_decode($key, ENT_QUOTES);
958
            }
959 1
            if (is_string($value)) {
960 1
                $d[$key] = htmlspecialchars_decode($value, ENT_QUOTES);
961 1
            } elseif (is_array($value)) {
962 1
                $d[$key] = static::htmlDecode($value);
963
            } else {
964
                /** @var mixed */
965 1
                $d[$key] = $value;
966
            }
967
        }
968
969 1
        return $d;
970
    }
971
972
    /**
973
     * Returns a value indicating whether the given array is an associative array.
974
     *
975
     * An array is associative if all its keys are strings. If `$allStrings` is false,
976
     * then an array will be treated as associative if at least one of its keys is a string.
977
     *
978
     * Note that an empty array will NOT be considered associative.
979
     *
980
     * @param array $array the array being checked
981
     * @param bool $allStrings whether the array keys must be all strings in order for
982
     * the array to be treated as associative.
983
     *
984
     * @return bool whether the array is associative
985
     */
986 1
    public static function isAssociative(array $array, bool $allStrings = true): bool
987
    {
988 1
        if ($array === []) {
989 1
            return false;
990
        }
991
992 1
        if ($allStrings) {
993
            /** @psalm-suppress MixedAssignment */
994 1
            foreach ($array as $key => $value) {
995 1
                if (!is_string($key)) {
996 1
                    return false;
997
                }
998
            }
999
1000 1
            return true;
1001
        }
1002
1003
        /** @psalm-suppress MixedAssignment */
1004 1
        foreach ($array as $key => $value) {
1005 1
            if (is_string($key)) {
1006 1
                return true;
1007
            }
1008
        }
1009
1010 1
        return false;
1011
    }
1012
1013
    /**
1014
     * Returns a value indicating whether the given array is an indexed array.
1015
     *
1016
     * An array is indexed if all its keys are integers. If `$consecutive` is true,
1017
     * then the array keys must be a consecutive sequence starting from 0.
1018
     *
1019
     * Note that an empty array will be considered indexed.
1020
     *
1021
     * @param array $array the array being checked
1022
     * @param bool $consecutive whether the array keys must be a consecutive sequence
1023
     * in order for the array to be treated as indexed.
1024
     *
1025
     * @return bool whether the array is indexed
1026
     */
1027 1
    public static function isIndexed(array $array, bool $consecutive = false): bool
1028
    {
1029 1
        if ($array === []) {
1030 1
            return true;
1031
        }
1032
1033 1
        if ($consecutive) {
1034 1
            return array_keys($array) === range(0, count($array) - 1);
1035
        }
1036
1037
        /** @psalm-var mixed $value */
1038 1
        foreach ($array as $key => $value) {
1039 1
            if (!is_int($key)) {
1040 1
                return false;
1041
            }
1042
        }
1043
1044 1
        return true;
1045
    }
1046
1047
    /**
1048
     * Check whether an array or `\Traversable` contains an element.
1049
     *
1050
     * This method does the same as the PHP function [in_array()](https://php.net/manual/en/function.in-array.php)
1051
     * but additionally works for objects that implement the `\Traversable` interface.
1052
     *
1053
     * @param mixed $needle The value to look for.
1054
     * @param iterable $haystack The set of values to search.
1055
     * @param bool $strict Whether to enable strict (`===`) comparison.
1056
     *
1057
     * @throws InvalidArgumentException if `$haystack` is neither traversable nor an array.
1058
     *
1059
     * @return bool `true` if `$needle` was found in `$haystack`, `false` otherwise.
1060
     *
1061
     * @see https://php.net/manual/en/function.in-array.php
1062
     */
1063 3
    public static function isIn($needle, iterable $haystack, bool $strict = false): bool
1064
    {
1065 3
        if (is_array($haystack)) {
1066 3
            return in_array($needle, $haystack, $strict);
1067
        }
1068
1069
        /** @psalm-var mixed $value */
1070 3
        foreach ($haystack as $value) {
1071 3
            if ($needle == $value && (!$strict || $needle === $value)) {
1072 3
                return true;
1073
            }
1074
        }
1075
1076 3
        return false;
1077
    }
1078
1079
    /**
1080
     * Checks whether an array or `\Traversable` is a subset of another array or `\Traversable`.
1081
     *
1082
     * This method will return `true`, if all elements of `$needles` are contained in
1083
     * `$haystack`. If at least one element is missing, `false` will be returned.
1084
     *
1085
     * @param iterable $needles The values that must **all** be in `$haystack`.
1086
     * @param iterable $haystack The set of value to search.
1087
     * @param bool $strict Whether to enable strict (`===`) comparison.
1088
     *
1089
     * @throws InvalidArgumentException if `$haystack` or `$needles` is neither traversable nor an array.
1090
     *
1091
     * @return bool `true` if `$needles` is a subset of `$haystack`, `false` otherwise.
1092
     */
1093 1
    public static function isSubset(iterable $needles, iterable $haystack, bool $strict = false): bool
1094
    {
1095
        /** @psalm-var mixed $needle */
1096 1
        foreach ($needles as $needle) {
1097 1
            if (!static::isIn($needle, $haystack, $strict)) {
1098 1
                return false;
1099
            }
1100
        }
1101
1102 1
        return true;
1103
    }
1104
1105
    /**
1106
     * Filters array according to rules specified.
1107
     *
1108
     * For example:
1109
     *
1110
     * ```php
1111
     * $array = [
1112
     *     'A' => [1, 2],
1113
     *     'B' => [
1114
     *         'C' => 1,
1115
     *         'D' => 2,
1116
     *     ],
1117
     *     'E' => 1,
1118
     * ];
1119
     *
1120
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['A']);
1121
     * // $result will be:
1122
     * // [
1123
     * //     'A' => [1, 2],
1124
     * // ]
1125
     *
1126
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['A', 'B.C']);
1127
     * // $result will be:
1128
     * // [
1129
     * //     'A' => [1, 2],
1130
     * //     'B' => ['C' => 1],
1131
     * // ]
1132
     *
1133
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['B', '!B.C']);
1134
     * // $result will be:
1135
     * // [
1136
     * //     'B' => ['D' => 2],
1137
     * // ]
1138
     * ```
1139
     *
1140
     * @param array $array Source array
1141
     * @param array $filters Rules that define array keys which should be left or removed from results.
1142
     * Each rule is:
1143
     * - `var` - `$array['var']` will be left in result.
1144
     * - `var.key` = only `$array['var']['key']` will be left in result.
1145
     * - `!var.key` = `$array['var']['key']` will be removed from result.
1146
     *
1147
     * @return array Filtered array
1148
     */
1149 3
    public static function filter(array $array, array $filters): array
1150
    {
1151 3
        $result = [];
1152 3
        $excludeFilters = [];
1153
1154 3
        foreach ($filters as $filter) {
1155 3
            if ($filter[0] === '!') {
1156 1
                $excludeFilters[] = substr($filter, 1);
1157 1
                continue;
1158
            }
1159
1160 3
            $nodeValue = $array; //set $array as root node
1161 3
            $keys = explode('.', $filter);
1162 3
            foreach ($keys as $key) {
1163 3
                if (!array_key_exists($key, $nodeValue)) {
1164 1
                    continue 2; //Jump to next filter
1165
                }
1166 3
                $nodeValue = $nodeValue[$key];
1167
            }
1168
1169
            //We've found a value now let's insert it
1170 2
            $resultNode = &$result;
1171 2
            foreach ($keys as $key) {
1172 2
                if (!array_key_exists($key, $resultNode)) {
1173 2
                    $resultNode[$key] = [];
1174
                }
1175 2
                $resultNode = &$resultNode[$key];
1176
            }
1177 2
            $resultNode = $nodeValue;
1178
        }
1179
1180 3
        foreach ($excludeFilters as $filter) {
1181 1
            $excludeNode = &$result;
1182 1
            $keys = explode('.', $filter);
1183 1
            $numNestedKeys = count($keys) - 1;
1184 1
            foreach ($keys as $i => $key) {
1185 1
                if (!array_key_exists($key, $excludeNode)) {
1186 1
                    continue 2; //Jump to next filter
1187
                }
1188
1189 1
                if ($i < $numNestedKeys) {
1190
                    /** @psalm-suppress EmptyArrayAccess */
1191 1
                    $excludeNode = &$excludeNode[$key];
1192
                } else {
1193
                    /** @psalm-suppress EmptyArrayAccess */
1194 1
                    unset($excludeNode[$key]);
1195 1
                    break;
1196
                }
1197
            }
1198
        }
1199
1200 3
        return $result;
1201
    }
1202
1203
    /**
1204
     * Returns the public member variables of an object.
1205
     * This method is provided such that we can get the public member variables of an object.
1206
     * It is different from `get_object_vars()` because the latter will return private
1207
     * and protected variables if it is called within the object itself.
1208
     *
1209
     * @param object $object the object to be handled
1210
     *
1211
     * @return array|null the public member variables of the object or null if not object given
1212
     *
1213
     * @see https://www.php.net/manual/en/function.get-object-vars.php
1214
     */
1215 4
    public static function getObjectVars(object $object): ?array
1216
    {
1217 4
        return get_object_vars($object);
1218
    }
1219
1220
    /**
1221
     * @param float|int|string $key
1222
     *
1223
     * @return string
1224
     */
1225 118
    private static function normalizeArrayKey($key): string
1226
    {
1227 118
        return is_float($key) ? NumericHelper::normalize($key) : (string)$key;
1228
    }
1229
}
1230