Passed
Push — master ( eb3fad...6278c6 )
by Sergei
08:48 queued 06:25
created

ArrayHelper::getValue()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 23
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

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

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