Passed
Push — master ( 90efab...3fad71 )
by Alexander
01:23
created

ArrayHelper::merge()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 10
cc 3
nc 2
nop 1
crap 3
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
     * @return array the array representation of the object
62
     */
63 6
    public static function toArray($object, array $properties = [], bool $recursive = true): array
64
    {
65 6
        if (is_array($object)) {
66 5
            if ($recursive) {
67 4
                foreach ($object as $key => $value) {
68 4
                    if (is_array($value) || is_object($value)) {
69 4
                        $object[$key] = static::toArray($value, $properties, true);
70
                    }
71
                }
72
            }
73
74 5
            return $object;
75
        }
76
77 4
        if (is_object($object)) {
78 4
            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 1
                        if (is_int($key)) {
84 1
                            $result[$name] = $object->$name;
85
                        } else {
86 1
                            $result[$key] = static::getValue($object, $name);
87
                        }
88
                    }
89
90 1
                    return $recursive ? static::toArray($result, $properties) : $result;
91
                }
92
            }
93 4
            if ($object instanceof ArrayableInterface) {
94 3
                $result = $object->toArray([], [], $recursive);
95
            } else {
96 4
                $result = [];
97 4
                foreach ($object as $key => $value) {
98 4
                    $result[$key] = $value;
99
                }
100
            }
101
102 4
            return $recursive ? static::toArray($result, $properties) : $result;
103
        }
104
105 1
        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
     * @return array the merged array (the original arrays are not changed)
119
     */
120 13
    public static function merge(...$args): array
121
    {
122 13
        $lastArray = end($args);
123 13
        if (isset($lastArray[ReverseBlockMerge::class]) && $lastArray[ReverseBlockMerge::class] instanceof ReverseBlockMerge) {
124 3
            reset($args);
125 3
            return self::applyModifiers(self::performReverseBlockMerge(...$args));
126
        }
127
128 10
        return self::applyModifiers(self::performMerge(...$args));
129
    }
130
131 10
    private static function performMerge(array ...$args): array
132
    {
133 10
        $res = array_shift($args) ?: [];
134 10
        while (!empty($args)) {
135 9
            foreach (array_shift($args) as $k => $v) {
136 9
                if (is_int($k)) {
137 5
                    if (array_key_exists($k, $res) && $res[$k] !== $v) {
138 3
                        $res[] = $v;
139
                    } else {
140 5
                        $res[$k] = $v;
141
                    }
142 7
                } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
143 3
                    $res[$k] = self::performMerge($res[$k], $v);
144
                } else {
145 7
                    $res[$k] = $v;
146
                }
147
            }
148
        }
149
150 10
        return $res;
151
    }
152
153 3
    private static function performReverseBlockMerge(array ...$args): array
154
    {
155 3
        $res = array_pop($args) ?: [];
156 3
        while (!empty($args)) {
157 3
            foreach (array_pop($args) as $k => $v) {
158 3
                if (is_int($k)) {
159 2
                    if (array_key_exists($k, $res) && $res[$k] !== $v) {
160 2
                        $res[] = $v;
161
                    } else {
162 2
                        $res[$k] = $v;
163
                    }
164 1
                } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
165 1
                    $res[$k] = self::performReverseBlockMerge($v, $res[$k]);
166 1
                } elseif (!isset($res[$k])) {
167 1
                    $res[$k] = $v;
168
                }
169
            }
170
        }
171
172 3
        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
     * @see ModifierInterface
184
     */
185 14
    public static function applyModifiers(array $data): array
186
    {
187 14
        $modifiers = [];
188 14
        foreach ($data as $k => $v) {
189 13
            if ($v instanceof ModifierInterface) {
190 9
                $modifiers[$k] = $v;
191 9
                unset($data[$k]);
192 13
            } elseif (is_array($v)) {
193 7
                $data[$k] = self::applyModifiers($v);
194
            }
195
        }
196 14
        ksort($modifiers);
197 14
        foreach ($modifiers as $key => $modifier) {
198 9
            $data = $modifier->apply($data, $key);
199
        }
200 14
        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
     * @return mixed the value of the element if found, default value otherwise
232
     */
233 65
    public static function getValue($array, $key, $default = null)
234
    {
235 65
        if ($key instanceof Closure) {
236 8
            return $key($array, $default);
237
        }
238
239
        /** @psalm-suppress DocblockTypeContradiction */
240 62
        if (!is_array($array) && !is_object($array)) {
241 1
            throw new \InvalidArgumentException(
242 1
                'getValue() can not get value from ' . gettype($array) . '. Only array and object are supported.'
243
            );
244
        }
245
246 61
        if (is_array($key)) {
247 37
            $lastKey = array_pop($key);
248 37
            foreach ($key as $keyPart) {
249 34
                $array = static::getRootValue($array, $keyPart, $default);
250
            }
251 37
            return static::getRootValue($array, $lastKey, $default);
252
        }
253
254 26
        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
     * @return mixed the value of the element if found, default value otherwise
263
     */
264 61
    private static function getRootValue($array, $key, $default)
265
    {
266 61
        if (is_array($array)) {
267 49
            $key = static::normalizeArrayKey($key);
268 49
            return array_key_exists($key, $array) ? $array[$key] : $default;
269
        }
270
271 22
        if (is_object($array)) {
272
            try {
273 14
                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 14
                return $array->$key;
278
            }
279
        }
280
281 8
        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
     * @param string $delimiter
320
     * @return mixed the value of the element if found, default value otherwise
321
     */
322 33
    public static function getValueByPath($array, $path, $default = null, string $delimiter = '.')
323
    {
324 33
        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
     * if the path is null then `$array` will be assigned the `$value`
360
     * @param mixed $value the value to be written
361
     */
362 29
    public static function setValue(array &$array, $key, $value): void
363
    {
364 29
        if ($key === null) {
365 2
            $array = $value;
366 2
            return;
367
        }
368
369 27
        $keys = is_array($key) ? $key : [$key];
370
371 27
        while (count($keys) > 1) {
372 15
            $k = static::normalizeArrayKey(array_shift($keys));
373 15
            if (!isset($array[$k])) {
374 8
                $array[$k] = [];
375
            }
376 15
            if (!is_array($array[$k])) {
377 2
                $array[$k] = [$array[$k]];
378
            }
379 15
            $array = &$array[$k];
380
        }
381
382 27
        $array[static::normalizeArrayKey(array_shift($keys))] = $value;
383 27
    }
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
     * @param mixed $value the value to be written
436
     * @param string $delimiter
437
     */
438 21
    public static function setValueByPath(array &$array, $path, $value, string $delimiter = '.'): void
439
    {
440 21
        static::setValue($array, static::parsePath($path, $delimiter), $value);
441 21
    }
442
443
    /**
444
     * @param mixed $path
445
     * @param string $delimiter
446
     * @return mixed
447
     */
448 58
    private static function parsePath($path, string $delimiter)
449
    {
450 58
        if (is_string($path)) {
451 52
            return explode($delimiter, $path);
452
        }
453 18
        if (is_array($path)) {
454 12
            $newPath = [];
455 12
            foreach ($path as $key) {
456 12
                if (is_string($key) || is_array($key)) {
457 12
                    $newPath = array_merge($newPath, static::parsePath($key, $delimiter));
458
                } else {
459 2
                    $newPath[] = $key;
460
                }
461
            }
462 12
            return $newPath;
463
        }
464 6
        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
     * @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
     */
486 13
    public static function remove(array &$array, $key, $default = null)
487
    {
488 13
        $keys = is_array($key) ? $key : [$key];
489
490 13
        while (count($keys) > 1) {
491 7
            $key = static::normalizeArrayKey(array_shift($keys));
492 7
            if (!isset($array[$key]) || !is_array($array[$key])) {
493 1
                return $default;
494
            }
495 6
            $array = &$array[$key];
496
        }
497
498 12
        $key = static::normalizeArrayKey(array_shift($keys));
499 12
        if (array_key_exists($key, $array)) {
500 11
            $value = $array[$key];
501 11
            unset($array[$key]);
502 11
            return $value;
503
        }
504
505 1
        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
     * @param string $delimiter
527
     * @return mixed the value of the element if found, default value otherwise
528
     */
529 5
    public static function removeByPath(array &$array, $path, $default = null, string $delimiter = '.')
530
    {
531 5
        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
     * @param mixed $value the value to remove from the array
549
     * @return array the items that were removed from the array
550
     */
551 2
    public static function removeValue(array &$array, $value): array
552
    {
553 2
        $result = [];
554 2
        foreach ($array as $key => $val) {
555 2
            if ($val === $value) {
556 1
                $result[$key] = $val;
557 1
                unset($array[$key]);
558
            }
559
        }
560
561 2
        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
     * to the result array without any key.
662
     * @return array the indexed and/or grouped array
663
     */
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 3
            $lastArray = &$result;
671
672 3
            foreach ($groups as $group) {
673 1
                $value = static::getValue($element, $group);
674 1
                if (!array_key_exists($value, $lastArray)) {
675 1
                    $lastArray[$value] = [];
676
                }
677 1
                $lastArray = &$lastArray[$value];
678
            }
679
680 3
            if ($key === null) {
681 2
                if (!empty($groups)) {
682 2
                    $lastArray[] = $element;
683
                }
684
            } else {
685 3
                $value = static::getValue($element, $key);
686 3
                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 88
    private static function normalizeArrayKey($key): string
1116
    {
1117 88
        return is_float($key) ? NumericHelper::normalize($key) : (string)$key;
1118
    }
1119
}
1120