Passed
Pull Request — master (#62)
by Alexander
07:46
created

ArrayHelper   F

Complexity

Total Complexity 130

Size/Duplication

Total Lines 1184
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 11
Bugs 0 Features 0
Metric Value
wmc 130
eloc 239
dl 0
loc 1184
ccs 260
cts 260
cp 1
rs 2
c 11
b 0
f 0

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