Passed
Push — master ( f54976...ede55f )
by Sergei
02:26
created

ArrayHelper::pathExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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