Passed
Pull Request — master (#59)
by Sergei
11:16
created

ArrayHelper   F

Complexity

Total Complexity 144

Size/Duplication

Total Lines 1101
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 10
Bugs 0 Features 0
Metric Value
wmc 144
eloc 255
c 10
b 0
f 0
dl 0
loc 1101
ccs 270
cts 270
cp 1
rs 2

27 Methods

Rating   Name   Duplication   Size   Complexity  
B filter() 0 52 11
B isAssociative() 0 23 7
A isIn() 0 13 6
A getObjectVars() 0 3 1
A isIndexed() 0 17 5
A htmlDecode() 0 17 6
A keyExists() 0 13 4
A getColumn() 0 14 4
A htmlEncode() 0 19 6
A map() 0 13 3
A isSubset() 0 9 3
A setValue() 0 21 6
A applyModifiers() 0 16 5
A getValueByPath() 0 3 1
B performReverseBlockMerge() 0 20 11
B index() 0 30 7
A remove() 0 20 6
A parsePath() 0 17 6
C toArray() 0 43 15
A removeByPath() 0 3 1
A getValue() 0 22 6
A setValueByPath() 0 3 1
A removeValue() 0 11 3
A normalizeArrayKey() 0 3 2
A merge() 0 9 3
A getRootValue() 0 18 5
B performMerge() 0 20 10

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