Passed
Push — master ( 7af88e...65f17b )
by Sergei
02:15
created

ArrayHelper::normalizeArrayKey()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

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

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
1186
     * Each rule is:
1187
     * - `var` - `$array['var']` will be left in result.
1188
     * - `var.key` = only `$array['var']['key']` will be left in result.
1189
     * - `!var.key` = `$array['var']['key']` will be removed from result.
1190
     *
1191
     * @return array Filtered array.
1192
     */
1193 17
    public static function filter(array $array, array $filters): array
1194
    {
1195 17
        $result = [];
1196 17
        $excludeFilters = [];
1197
1198 17
        foreach ($filters as $filter) {
1199 17
            if ($filter[0] === '!') {
1200 6
                $excludeFilters[] = substr($filter, 1);
1201 6
                continue;
1202
            }
1203
1204 17
            $nodeValue = $array; // Set $array as root node.
1205 17
            $keys = explode('.', $filter);
1206 17
            foreach ($keys as $key) {
1207 17
                if (!is_array($nodeValue) || !array_key_exists($key, $nodeValue)) {
1208 4
                    continue 2; // Jump to next filter.
1209
                }
1210
                /** @var mixed */
1211 15
                $nodeValue = $nodeValue[$key];
1212
            }
1213
1214
            // We've found a value now let's insert it.
1215 13
            $resultNode = &$result;
1216 13
            foreach ($keys as $key) {
1217 13
                if (!array_key_exists($key, $resultNode)) {
1218 13
                    $resultNode[$key] = [];
1219
                }
1220 13
                $resultNode = &$resultNode[$key];
1221
            }
1222
            /** @var mixed */
1223 13
            $resultNode = $nodeValue;
1224
        }
1225
1226
        /** @var array $result */
1227
1228 17
        foreach ($excludeFilters as $filter) {
1229 6
            $excludeNode = &$result;
1230 6
            $keys = explode('.', $filter);
1231 6
            $numNestedKeys = count($keys) - 1;
1232 6
            foreach ($keys as $i => $key) {
1233 6
                if (!is_array($excludeNode) || !array_key_exists($key, $excludeNode)) {
1234 2
                    continue 2; // Jump to next filter.
1235
                }
1236
1237 5
                if ($i < $numNestedKeys) {
1238
                    /** @var mixed */
1239 5
                    $excludeNode = &$excludeNode[$key];
1240
                } else {
1241 4
                    unset($excludeNode[$key]);
1242 4
                    break;
1243
                }
1244
            }
1245
        }
1246
1247 17
        return $result;
1248
    }
1249
1250
    /**
1251
     * Returns the public member variables of an object.
1252
     *
1253
     * This method is provided such that we can get the public member variables of an object, because a direct call of
1254
     * {@see get_object_vars()} (within the object itself) will return only private and protected variables.
1255
     *
1256
     * @param object $object The object to be handled.
1257
     *
1258
     * @return array|null The public member variables of the object or null if not object given.
1259
     *
1260
     * @link https://www.php.net/manual/en/function.get-object-vars.php
1261
     */
1262 4
    public static function getObjectVars(object $object): ?array
1263
    {
1264 4
        return get_object_vars($object);
1265
    }
1266
1267
    /**
1268
     * @param mixed $key
1269
     *
1270
     * @return string
1271
     */
1272 142
    private static function normalizeArrayKey($key): string
1273
    {
1274 142
        return is_float($key) ? NumericHelper::normalize($key) : (string)$key;
1275
    }
1276
1277
    /**
1278
     * @param array|float|int|string $path
1279
     * @param string $delimiter
1280
     *
1281
     * @psalm-param ArrayPath $path
1282
     *
1283
     * @return array|float|int|string
1284
     * @psalm-return ArrayKey
1285
     */
1286 86
    private static function parseMixedPath($path, string $delimiter)
1287
    {
1288 86
        if (is_array($path)) {
1289 17
            $newPath = [];
1290 17
            foreach ($path as $key) {
1291 17
                if (is_string($key)) {
1292 17
                    $parsedPath = StringHelper::parsePath($key, $delimiter);
1293 17
                    $newPath = array_merge($newPath, $parsedPath);
1294 17
                    continue;
1295
                }
1296
1297 8
                if (is_array($key)) {
1298
                    /** @var list<float|int|string> $parsedPath */
1299 4
                    $parsedPath = self::parseMixedPath($key, $delimiter);
1300 4
                    $newPath = array_merge($newPath, $parsedPath);
0 ignored issues
show
Bug introduced by
$parsedPath of type Yiisoft\Arrays\list is incompatible with the type array expected by parameter $arrays of array_merge(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1300
                    $newPath = array_merge($newPath, /** @scrutinizer ignore-type */ $parsedPath);
Loading history...
1301 4
                    continue;
1302
                }
1303
1304 4
                $newPath[] = $key;
1305
            }
1306 17
            return $newPath;
1307
        }
1308
1309 70
        return is_string($path) ? StringHelper::parsePath($path, $delimiter) : $path;
1310
    }
1311
}
1312