Passed
Push — master ( f0ae8f...3f9979 )
by Alexander
02:17
created

ArrayHelper::group()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Arrays;
6
7
use Closure;
8
use InvalidArgumentException;
9
use Throwable;
10
use Yiisoft\Strings\NumericHelper;
11
12
use function array_key_exists;
13
use function get_class;
14
use function in_array;
15
use function is_array;
16
use function is_float;
17
use function is_int;
18
use function is_object;
19
use function is_string;
20
21
/**
22
 * Yii array helper provides static methods allowing you to deal with arrays more efficiently.
23
 *
24
 * @psalm-type ArrayKey = float|int|string|list<float|int|string>
25
 * @psalm-type ArrayPath = float|int|string|list<float|int|string|list<float|int|string>>
26
 */
27
class ArrayHelper
28
{
29
    /**
30
     * Converts an object or an array of objects into an array.
31
     *
32
     * For example:
33
     *
34
     * ```php
35
     * [
36
     *     Post::class => [
37
     *         'id',
38
     *         'title',
39
     *         'createTime' => 'created_at',
40
     *         'length' => function ($post) {
41
     *             return strlen($post->content);
42
     *         },
43
     *     ],
44
     * ]
45
     * ```
46
     *
47
     * The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
48
     *
49
     * ```php
50
     * [
51
     *     'id' => 123,
52
     *     'title' => 'test',
53
     *     'createTime' => '2013-01-01 12:00AM',
54
     *     'length' => 301,
55
     * ]
56
     * ```
57
     *
58
     * @param array|object|string $object The object to be converted into an array.
59
     *
60
     * It is possible to provide default way of converting object to array for a specific class by implementing
61
     * {@see \Yiisoft\Arrays\ArrayableInterface} in its class.
62
     * @param array $properties A mapping from object class names to the properties that need to put into
63
     * the resulting arrays. The properties specified for each class is an array of the following format:
64
     *
65
     * - A field name to include as is.
66
     * - A key-value pair of desired array key name and model column name to take value from.
67
     * - A key-value pair of desired array key name and a callback which returns value.
68
     * @param bool $recursive Whether to recursively converts properties which are objects into arrays.
69
     *
70
     * @return array The array representation of the object.
71
     */
72 6
    public static function toArray($object, array $properties = [], bool $recursive = true): array
73
    {
74 6
        if (is_array($object)) {
75 5
            if ($recursive) {
76
                /** @var mixed $value */
77 4
                foreach ($object as $key => $value) {
78 4
                    if (is_array($value) || is_object($value)) {
79 4
                        $object[$key] = static::toArray($value, $properties);
80
                    }
81
                }
82
            }
83
84 5
            return $object;
85
        }
86
87 4
        if (is_object($object)) {
88 4
            if (!empty($properties)) {
89 1
                $className = get_class($object);
90 1
                if (!empty($properties[$className])) {
91 1
                    $result = [];
92
                    /**
93
                     * @var int|string $key
94
                     * @var string $name
95
                     */
96 1
                    foreach ($properties[$className] as $key => $name) {
97 1
                        if (is_int($key)) {
98
                            /** @var mixed */
99 1
                            $result[$name] = $object->$name;
100
                        } else {
101
                            /** @var mixed */
102 1
                            $result[$key] = static::getValue($object, $name);
103
                        }
104
                    }
105
106 1
                    return $recursive ? static::toArray($result, $properties) : $result;
107
                }
108
            }
109 4
            if ($object instanceof ArrayableInterface) {
110 3
                $result = $object->toArray([], [], $recursive);
111
            } else {
112 4
                $result = [];
113
                /**
114
                 * @var string $key
115
                 * @var mixed $value
116
                 */
117 4
                foreach ($object as $key => $value) {
118
                    /** @var mixed */
119 4
                    $result[$key] = $value;
120
                }
121
            }
122
123 4
            return $recursive ? static::toArray($result, $properties) : $result;
124
        }
125
126 1
        return [$object];
127
    }
128
129
    /**
130
     * Merges two or more arrays into one recursively.
131
     * If each array has an element with the same string key value, the latter
132
     * will overwrite the former (different from {@see array_merge_recursive()}).
133
     * Recursive merging will be conducted if both arrays have an element of array
134
     * type and are having the same key.
135
     * For integer-keyed elements, the elements from the latter array will
136
     * be appended to the former array.
137
     *
138
     * @param array ...$arrays Arrays to be merged.
139
     *
140
     * @return array The merged array (the original arrays are not changed).
141
     */
142 4
    public static function merge(...$arrays): array
143
    {
144 4
        $result = array_shift($arrays) ?: [];
145 4
        while (!empty($arrays)) {
146
            /** @var mixed $value */
147 3
            foreach (array_shift($arrays) as $key => $value) {
148 3
                if (is_int($key)) {
149 3
                    if (array_key_exists($key, $result)) {
150 3
                        if ($result[$key] !== $value) {
151
                            /** @var mixed */
152 3
                            $result[] = $value;
153
                        }
154
                    } else {
155
                        /** @var mixed */
156 3
                        $result[$key] = $value;
157
                    }
158 1
                } elseif (isset($result[$key]) && is_array($value) && is_array($result[$key])) {
159 1
                    $result[$key] = self::merge($result[$key], $value);
160
                } else {
161
                    /** @var mixed */
162 1
                    $result[$key] = $value;
163
                }
164
            }
165
        }
166 4
        return $result;
167
    }
168
169
    /**
170
     * Retrieves the value of an array element or object property with the given key or property name.
171
     * If the key does not exist in the array or object, the default value will be returned instead.
172
     *
173
     * Below are some usage examples,
174
     *
175
     * ```php
176
     * // Working with array:
177
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($_POST, 'username');
178
     *
179
     * // Working with object:
180
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($user, 'username');
181
     *
182
     * // Working with anonymous function:
183
     * $fullName = \Yiisoft\Arrays\ArrayHelper::getValue($user, function ($user, $defaultValue) {
184
     *     return $user->firstName . ' ' . $user->lastName;
185
     * });
186
     *
187
     * // Using an array of keys to retrieve the value:
188
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
189
     * ```
190
     *
191
     * @param array|object $array Array or object to extract value from.
192
     * @param array|Closure|float|int|string $key Key name of the array element,
193
     * an array of keys or property name of the object, or an anonymous function
194
     * returning the value. The anonymous function signature should be:
195
     * `function($array, $defaultValue)`.
196
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
197
     * getting value from an object.
198
     *
199
     * @psalm-param ArrayKey|Closure $key
200
     *
201
     * @return mixed The value of the element if found, default value otherwise.
202
     */
203 69
    public static function getValue($array, $key, $default = null)
204
    {
205 69
        if ($key instanceof Closure) {
206 9
            return $key($array, $default);
207
        }
208
209
        /** @psalm-suppress DocblockTypeContradiction */
210 66
        if (!is_array($array) && !is_object($array)) {
211 1
            throw new InvalidArgumentException(
212 1
                'getValue() can not get value from ' . gettype($array) . '. Only array and object are supported.'
213
            );
214
        }
215
216 65
        if (is_array($key)) {
217
            /** @psalm-var array<mixed,string|int> $key */
218 37
            $lastKey = array_pop($key);
219 37
            foreach ($key as $keyPart) {
220
                /** @var mixed */
221 34
                $array = static::getRootValue($array, $keyPart, $default);
222
            }
223 37
            return static::getRootValue($array, $lastKey, $default);
224
        }
225
226 30
        return static::getRootValue($array, $key, $default);
227
    }
228
229
    /**
230
     * @param mixed $array Array or object to extract value from, otherwise method will return $default.
231
     * @param float|int|string $key Key name of the array element or property name of the object.
232
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
233
     * getting value from an object.
234
     *
235
     * @return mixed The value of the element if found, default value otherwise.
236
     */
237 92
    private static function getRootValue($array, $key, $default)
238
    {
239 92
        if (is_array($array)) {
240 80
            $key = static::normalizeArrayKey($key);
241 80
            return array_key_exists($key, $array) ? $array[$key] : $default;
242
        }
243
244 22
        if (is_object($array)) {
245
            try {
246 14
                return $array::$$key;
247 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...
248
                // This is expected to fail if the property does not exist, or __get() is not implemented.
249
                // It is not reliably possible to check whether a property is accessible beforehand.
250 14
                return $array->$key;
251
            }
252
        }
253
254 8
        return $default;
255
    }
256
257
    /**
258
     * Retrieves the value of an array element or object property with the given key or property name.
259
     * If the key does not exist in the array or object, the default value will be returned instead.
260
     *
261
     * The key may be specified in a dot-separated format to retrieve the value of a sub-array or the property
262
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
263
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
264
     * or `$array->x` is neither an array nor an object, the default value will be returned.
265
     * Note that if the array already has an element `x.y.z`, then its value will be returned
266
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
267
     * like `['x', 'y', 'z']`.
268
     *
269
     * Below are some usage examples,
270
     *
271
     * ```php
272
     * // Using separated format to retrieve the property of embedded object:
273
     * $street = \Yiisoft\Arrays\ArrayHelper::getValue($users, 'address.street');
274
     *
275
     * // Using an array of keys to retrieve the value:
276
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
277
     * ```
278
     *
279
     * @param array|object $array Array or object to extract value from.
280
     * @param array|Closure|float|int|string $path Key name of the array element, an array of keys or property name
281
     * of the object, or an anonymous function returning the value. The anonymous function signature should be:
282
     * `function($array, $defaultValue)`.
283
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
284
     * getting value from an object.
285
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
286
     * to "." (dot).
287
     *
288
     * @psalm-param ArrayPath|Closure $path
289
     *
290
     * @return mixed The value of the element if found, default value otherwise.
291
     */
292 33
    public static function getValueByPath($array, $path, $default = null, string $delimiter = '.')
293
    {
294 33
        return static::getValue(
295 33
            $array,
296 33
            $path instanceof Closure ? $path : static::parsePath($path, $delimiter),
297
            $default
298
        );
299
    }
300
301
    /**
302
     * Writes a value into an associative array at the key path specified.
303
     * If there is no such key path yet, it will be created recursively.
304
     * If the key exists, it will be overwritten.
305
     *
306
     * ```php
307
     *  $array = [
308
     *      'key' => [
309
     *          'in' => [
310
     *              'val1',
311
     *              'key' => 'val'
312
     *          ]
313
     *      ]
314
     *  ];
315
     * ```
316
     *
317
     * The result of `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
318
     * will be the following:
319
     *
320
     * ```php
321
     *  [
322
     *      'key' => [
323
     *          'in' => [
324
     *              'arr' => 'val'
325
     *          ]
326
     *      ]
327
     *  ]
328
     * ```
329
     *
330
     * @param array $array The array to write the value to.
331
     * @param array|float|int|string|null $key The path of where do you want to write a value to `$array`
332
     * the path can be described by an array of keys. If the path is null then `$array` will be assigned the `$value`.
333
     *
334
     * @psalm-param ArrayKey|null $key
335
     *
336
     * @param mixed $value The value to be written.
337
     */
338 29
    public static function setValue(array &$array, $key, $value): void
339
    {
340 29
        if ($key === null) {
341
            /** @var mixed */
342 2
            $array = $value;
343 2
            return;
344
        }
345
346 27
        $keys = is_array($key) ? $key : [$key];
347
348 27
        while (count($keys) > 1) {
349 15
            $k = static::normalizeArrayKey(array_shift($keys));
350 15
            if (!isset($array[$k])) {
351 8
                $array[$k] = [];
352
            }
353 15
            if (!is_array($array[$k])) {
354 2
                $array[$k] = [$array[$k]];
355
            }
356 15
            $array = &$array[$k];
357
        }
358
359
        /** @var mixed */
360 27
        $array[static::normalizeArrayKey(array_shift($keys))] = $value;
361 27
    }
362
363
    /**
364
     * Writes a value into an associative array at the key path specified.
365
     * If there is no such key path yet, it will be created recursively.
366
     * If the key exists, it will be overwritten.
367
     *
368
     * ```php
369
     *  $array = [
370
     *      'key' => [
371
     *          'in' => [
372
     *              'val1',
373
     *              'key' => 'val'
374
     *          ]
375
     *      ]
376
     *  ];
377
     * ```
378
     *
379
     * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
380
     *
381
     * ```php
382
     *  [
383
     *      'key' => [
384
     *          'in' => [
385
     *              ['arr' => 'val'],
386
     *              'key' => 'val'
387
     *          ]
388
     *      ]
389
     *  ]
390
     *
391
     * ```
392
     *
393
     * The result of
394
     * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
395
     * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
396
     * will be the following:
397
     *
398
     * ```php
399
     *  [
400
     *      'key' => [
401
     *          'in' => [
402
     *              'arr' => 'val'
403
     *          ]
404
     *      ]
405
     *  ]
406
     * ```
407
     *
408
     * @param array $array The array to write the value to.
409
     * @param array|float|int|string|null $path The path of where do you want to write a value to `$array`.
410
     * The path can be described by a string when each key should be separated by a dot.
411
     * You can also describe the path as an array of keys. If the path is null then `$array` will be assigned
412
     * the `$value`.
413
     * @param mixed $value The value to be written.
414
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
415
     * to "." (dot).
416
     *
417
     * @psalm-param ArrayPath|null $path
418
     */
419 21
    public static function setValueByPath(array &$array, $path, $value, string $delimiter = '.'): void
420
    {
421 21
        static::setValue($array, $path === null ? null : static::parsePath($path, $delimiter), $value);
422 21
    }
423
424
    /**
425
     * @param array|float|int|string $path The path of where do you want to write a value to `$array`.
426
     * The path can be described by a string when each key should be separated by delimiter.
427
     * You can also describe the path as an array of keys.
428
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
429
     * to "." (dot).
430
     *
431
     * @psalm-param ArrayPath $path
432
     *
433
     * @return array|float|int|string
434
     * @psalm-return ArrayKey
435
     */
436 82
    private static function parsePath($path, string $delimiter)
437
    {
438 82
        if (is_string($path)) {
439 77
            return explode($delimiter, $path);
440
        }
441 22
        if (is_array($path)) {
442 17
            $newPath = [];
443 17
            foreach ($path as $key) {
444 17
                if (is_string($key) || is_array($key)) {
445
                    /** @var list<float|int|string> $parsedPath */
446 17
                    $parsedPath = static::parsePath($key, $delimiter);
447 17
                    $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

447
                    $newPath = array_merge($newPath, /** @scrutinizer ignore-type */ $parsedPath);
Loading history...
448
                } else {
449 4
                    $newPath[] = $key;
450
                }
451
            }
452 17
            return $newPath;
453
        }
454 5
        return $path;
455
    }
456
457
    /**
458
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
459
     * will be returned instead.
460
     *
461
     * Usage examples,
462
     *
463
     * ```php
464
     * // $array = ['type' => 'A', 'options' => [1, 2]];
465
     *
466
     * // Working with array:
467
     * $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
468
     *
469
     * // $array content
470
     * // $array = ['options' => [1, 2]];
471
     * ```
472
     *
473
     * @param array $array The array to extract value from.
474
     * @param array|float|int|string $key Key name of the array element or associative array at the key path specified.
475
     * @param mixed $default The default value to be returned if the specified key does not exist.
476
     *
477
     * @psalm-param ArrayKey $key
478
     *
479
     * @return mixed The value of the element if found, default value otherwise.
480
     */
481 13
    public static function remove(array &$array, $key, $default = null)
482
    {
483 13
        $keys = is_array($key) ? $key : [$key];
484
485 13
        while (count($keys) > 1) {
486 7
            $key = static::normalizeArrayKey(array_shift($keys));
487 7
            if (!isset($array[$key]) || !is_array($array[$key])) {
488 1
                return $default;
489
            }
490 6
            $array = &$array[$key];
491
        }
492
493 12
        $key = static::normalizeArrayKey(array_shift($keys));
494 12
        if (array_key_exists($key, $array)) {
495
            /** @var mixed */
496 11
            $value = $array[$key];
497 11
            unset($array[$key]);
498 11
            return $value;
499
        }
500
501 1
        return $default;
502
    }
503
504
    /**
505
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
506
     * will be returned instead.
507
     *
508
     * Usage examples,
509
     *
510
     * ```php
511
     * // $array = ['type' => 'A', 'options' => [1, 2]];
512
     *
513
     * // Working with array:
514
     * $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
515
     *
516
     * // $array content
517
     * // $array = ['options' => [1, 2]];
518
     * ```
519
     *
520
     * @param array $array The array to extract value from.
521
     * @param array|float|int|string $path Key name of the array element or associative array at the key path specified.
522
     * The path can be described by a string when each key should be separated by a delimiter (default is dot).
523
     * @param mixed $default The default value to be returned if the specified key does not exist.
524
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
525
     * to "." (dot).
526
     *
527
     * @psalm-param ArrayPath $path
528
     *
529
     * @return mixed The value of the element if found, default value otherwise.
530
     */
531 5
    public static function removeByPath(array &$array, $path, $default = null, string $delimiter = '.')
532
    {
533 5
        return static::remove($array, static::parsePath($path, $delimiter), $default);
534
    }
535
536
    /**
537
     * Removes items with matching values from the array and returns the removed items.
538
     *
539
     * Example,
540
     *
541
     * ```php
542
     * $array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
543
     * $removed = \Yiisoft\Arrays\ArrayHelper::removeValue($array, 'Jackson');
544
     * // result:
545
     * // $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
546
     * // $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
547
     * ```
548
     *
549
     * @param array $array The array where to look the value from.
550
     * @param mixed $value The value to remove from the array.
551
     *
552
     * @return array The items that were removed from the array.
553
     */
554 2
    public static function removeValue(array &$array, $value): array
555
    {
556 2
        $result = [];
557
        /** @psalm-var mixed $val */
558 2
        foreach ($array as $key => $val) {
559 2
            if ($val === $value) {
560
                /** @var mixed */
561 1
                $result[$key] = $val;
562 1
                unset($array[$key]);
563
            }
564
        }
565
566 2
        return $result;
567
    }
568
569
    /**
570
     * Indexes and/or groups the array according to a specified key.
571
     * The input should be either multidimensional array or an array of objects.
572
     *
573
     * The $key can be either a key name of the sub-array, a property name of object, or an anonymous
574
     * function that must return the value that will be used as a key.
575
     *
576
     * $groups is an array of keys, that will be used to group the input array into one or more sub-arrays based
577
     * on keys specified.
578
     *
579
     * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
580
     * to `$groups` not specified then the element is discarded.
581
     *
582
     * For example:
583
     *
584
     * ```php
585
     * $array = [
586
     *     ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
587
     *     ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
588
     *     ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
589
     * ];
590
     * $result = ArrayHelper::index($array, 'id');
591
     * ```
592
     *
593
     * The result will be an associative array, where the key is the value of `id` attribute
594
     *
595
     * ```php
596
     * [
597
     *     '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
598
     *     '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
599
     *     // The second element of an original array is overwritten by the last element because of the same id
600
     * ]
601
     * ```
602
     *
603
     * An anonymous function can be used in the grouping array as well.
604
     *
605
     * ```php
606
     * $result = ArrayHelper::index($array, function ($element) {
607
     *     return $element['id'];
608
     * });
609
     * ```
610
     *
611
     * Passing `id` as a third argument will group `$array` by `id`:
612
     *
613
     * ```php
614
     * $result = ArrayHelper::index($array, null, 'id');
615
     * ```
616
     *
617
     * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
618
     * and indexed by `data` on the third level:
619
     *
620
     * ```php
621
     * [
622
     *     '123' => [
623
     *         ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
624
     *     ],
625
     *     '345' => [ // all elements with this index are present in the result array
626
     *         ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
627
     *         ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
628
     *     ]
629
     * ]
630
     * ```
631
     *
632
     * The anonymous function can be used in the array of grouping keys as well:
633
     *
634
     * ```php
635
     * $result = ArrayHelper::index($array, 'data', [function ($element) {
636
     *     return $element['id'];
637
     * }, 'device']);
638
     * ```
639
     *
640
     * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
641
     * and indexed by the `data` on the third level:
642
     *
643
     * ```php
644
     * [
645
     *     '123' => [
646
     *         'laptop' => [
647
     *             'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
648
     *         ]
649
     *     ],
650
     *     '345' => [
651
     *         'tablet' => [
652
     *             'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
653
     *         ],
654
     *         'smartphone' => [
655
     *             'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
656
     *         ]
657
     *     ]
658
     * ]
659
     * ```
660
     *
661
     * @param array $array The array that needs to be indexed or grouped.
662
     * @param Closure|string|null $key The column name or anonymous function which result will be used
663
     * to index the array.
664
     * @param Closure[]|string|string[]|null $groups The array of keys, that will be used to group the input array
665
     * by one or more keys. If the $key attribute or its value for the particular element is null and $groups is not
666
     * defined, the array element will be discarded. Otherwise, if $groups is specified, array element will be added
667
     * to the result array without any key.
668
     *
669
     * @psalm-param array<mixed, array|object> $array
670
     *
671
     * @return array The indexed and/or grouped array.
672
     */
673 8
    public static function index(array $array, $key, $groups = []): array
674
    {
675 8
        $result = [];
676 8
        $groups = (array)$groups;
677
678 8
        foreach ($array as $element) {
679
            /** @psalm-suppress DocblockTypeContradiction */
680 8
            if (!is_array($element) && !is_object($element)) {
681 4
                throw new InvalidArgumentException(
682 4
                    'index() can not get value from ' . gettype($element)
683 4
                    . '. The $array should be either multidimensional array or an array of objects.'
684
                );
685
            }
686
687 6
            $lastArray = &$result;
688
689 6
            foreach ($groups as $group) {
690 2
                $value = static::normalizeArrayKey(
691 2
                    static::getValue($element, $group)
692
                );
693 2
                if (!array_key_exists($value, $lastArray)) {
694 2
                    $lastArray[$value] = [];
695
                }
696 2
                $lastArray = &$lastArray[$value];
697
            }
698
699 6
            if ($key === null) {
700 4
                if (!empty($groups)) {
701 4
                    $lastArray[] = $element;
702
                }
703
            } else {
704
                /** @var mixed */
705 4
                $value = static::getValue($element, $key);
706 4
                if ($value !== null) {
707 4
                    $lastArray[static::normalizeArrayKey($value)] = $element;
708
                }
709
            }
710 6
            unset($lastArray);
711
        }
712
713 4
        return $result;
714
    }
715
716
    /**
717
     * Groups the array according to a specified key.
718
     * This is just an alias for indexing by groups
719
     *
720
     * @param array $array The array that needs to be grouped.
721
     * @param Closure[]|string|string[] $groups The array of keys, that will be used to group the input array
722
     * by one or more keys.
723
     *
724
     * @psalm-param array<mixed, array|object> $array
725
     *
726
     * @return array The grouped array.
727
     */
728 1
    public static function group(array $array, $groups): array
729
    {
730 1
        return static::index($array, null, $groups);
731
    }
732
733
    /**
734
     * Returns the values of a specified column in an array.
735
     * The input array should be multidimensional or an array of objects.
736
     *
737
     * For example,
738
     *
739
     * ```php
740
     * $array = [
741
     *     ['id' => '123', 'data' => 'abc'],
742
     *     ['id' => '345', 'data' => 'def'],
743
     * ];
744
     * $result = ArrayHelper::getColumn($array, 'id');
745
     * // the result is: ['123', '345']
746
     *
747
     * // using anonymous function
748
     * $result = ArrayHelper::getColumn($array, function ($element) {
749
     *     return $element['id'];
750
     * });
751
     * ```
752
     *
753
     * @param array<array-key, array|object> $array The array to get column from.
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<array-key, array|object> at position 2 could not be parsed: Unknown type name 'array-key' at position 2 in array<array-key, array|object>.
Loading history...
754
     * @param Closure|string $name Column name or a closure returning column name.
755
     * @param bool $keepKeys Whether to maintain the array keys. If false, the resulting array
756
     * will be re-indexed with integers.
757
     *
758
     * @return array The list of column values.
759
     */
760 5
    public static function getColumn(array $array, $name, bool $keepKeys = true): array
761
    {
762 5
        $result = [];
763 5
        if ($keepKeys) {
764 5
            foreach ($array as $k => $element) {
765
                /** @var mixed */
766 5
                $result[$k] = static::getValue($element, $name);
767
            }
768
        } else {
769 1
            foreach ($array as $element) {
770
                /** @var mixed */
771 1
                $result[] = static::getValue($element, $name);
772
            }
773
        }
774
775 5
        return $result;
776
    }
777
778
    /**
779
     * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
780
     * The `$from` and `$to` parameters specify the key names or property names to set up the map.
781
     * Optionally, one can further group the map according to a grouping field `$group`.
782
     *
783
     * For example,
784
     *
785
     * ```php
786
     * $array = [
787
     *     ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
788
     *     ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
789
     *     ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
790
     * ];
791
     *
792
     * $result = ArrayHelper::map($array, 'id', 'name');
793
     * // the result is:
794
     * // [
795
     * //     '123' => 'aaa',
796
     * //     '124' => 'bbb',
797
     * //     '345' => 'ccc',
798
     * // ]
799
     *
800
     * $result = ArrayHelper::map($array, 'id', 'name', 'class');
801
     * // the result is:
802
     * // [
803
     * //     'x' => [
804
     * //         '123' => 'aaa',
805
     * //         '124' => 'bbb',
806
     * //     ],
807
     * //     'y' => [
808
     * //         '345' => 'ccc',
809
     * //     ],
810
     * // ]
811
     * ```
812
     *
813
     * @param array $array Array to build map from.
814
     * @param Closure|string $from Key or property name to map from.
815
     * @param Closure|string $to Key or property name to map to.
816
     * @param Closure|string|null $group Key or property to group the map.
817
     *
818
     * @psalm-param array<mixed, array|object> $array
819
     *
820
     * @return array Resulting map.
821
     */
822 3
    public static function map(array $array, $from, $to, $group = null): array
823
    {
824 3
        if ($group === null) {
825 2
            if ($from instanceof Closure || $to instanceof Closure) {
826 1
                $result = [];
827 1
                foreach ($array as $element) {
828 1
                    $key = (string)static::getValue($element, $from);
829
                    /** @var mixed */
830 1
                    $result[$key] = static::getValue($element, $to);
831
                }
832
833 1
                return $result;
834
            }
835
836 2
            return array_column($array, $to, $from);
837
        }
838
839 2
        $result = [];
840 2
        foreach ($array as $element) {
841 2
            $groupKey = (string)static::getValue($element, $group);
842 2
            $key = (string)static::getValue($element, $from);
843
            /** @var mixed */
844 2
            $result[$groupKey][$key] = static::getValue($element, $to);
845
        }
846
847 2
        return $result;
848
    }
849
850
    /**
851
     * Checks if the given array contains the specified key.
852
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
853
     * key comparison.
854
     *
855
     * @param array $array The array with keys to check.
856
     * @param array|float|int|string $key The key to check.
857
     * @param bool $caseSensitive Whether the key comparison should be case-sensitive.
858
     *
859
     * @psalm-param ArrayKey $key
860
     *
861
     * @return bool Whether the array contains the specified key.
862
     */
863 41
    public static function keyExists(array $array, $key, bool $caseSensitive = true): bool
864
    {
865 41
        if (is_array($key)) {
866 31
            if (count($key) === 1) {
867 25
                return static::rootKeyExists($array, end($key), $caseSensitive);
868
            }
869
870 27
            foreach (self::getExistsKeys($array, array_shift($key), $caseSensitive) as $existKey) {
871
                /** @var mixed */
872 27
                $array = static::getRootValue($array, $existKey, null);
873 27
                if (is_array($array) && self::keyExists($array, $key, $caseSensitive)) {
874 14
                    return true;
875
                }
876
            }
877
878 13
            return false;
879
        }
880
881 10
        return static::rootKeyExists($array, $key, $caseSensitive);
882
    }
883
884
    /**
885
     * @param array $array
886
     * @param float|int|string $key
887
     * @param bool $caseSensitive
888
     *
889
     * @return bool
890
     */
891 35
    private static function rootKeyExists(array $array, $key, bool $caseSensitive): bool
892
    {
893 35
        $key = (string)$key;
894
895 35
        if ($caseSensitive) {
896 29
            return array_key_exists($key, $array);
897
        }
898
899 6
        foreach (array_keys($array) as $k) {
900 6
            if (strcasecmp($key, (string)$k) === 0) {
901 5
                return true;
902
            }
903
        }
904
905 1
        return false;
906
    }
907
908
    /**
909
     * @param array $array
910
     * @param float|int|string $key
911
     * @param bool $caseSensitive
912
     *
913
     * @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...
914
     */
915 27
    private static function getExistsKeys(array $array, $key, bool $caseSensitive): array
916
    {
917 27
        $key = (string)$key;
918
919 27
        if ($caseSensitive) {
920 22
            return [$key];
921
        }
922
923 5
        return array_filter(
924 5
            array_keys($array),
925 5
            static fn ($k) => strcasecmp($key, (string)$k) === 0
926 5
        );
927
    }
928
929
    /**
930
     * Checks if the given array contains the specified key. The key may be specified in a dot format.
931
     * In particular, if the key is `x.y.z`, then key would be `$array['x']['y']['z']`.
932
     *
933
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
934
     * key comparison.
935
     *
936
     * @param array $array The array to check path in.
937
     * @param array|float|int|string $path The key path. Can be described by a string when each key should be separated
938
     * by delimiter. You can also describe the path as an array of keys.
939
     * @param bool $caseSensitive Whether the key comparison should be case-sensitive.
940
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
941
     * to "." (dot).
942
     *
943
     * @psalm-param ArrayPath $path
944
     *
945
     * @return bool
946
     */
947 26
    public static function pathExists(
948
        array $array,
949
        $path,
950
        bool $caseSensitive = true,
951
        string $delimiter = '.'
952
    ): bool {
953 26
        return static::keyExists($array, static::parsePath($path, $delimiter), $caseSensitive);
954
    }
955
956
    /**
957
     * Encodes special characters in an array of strings into HTML entities.
958
     * Only array values will be encoded by default.
959
     * If a value is an array, this method will also encode it recursively.
960
     * Only string values will be encoded.
961
     *
962
     * @param array $data Data to be encoded.
963
     * @param bool $valuesOnly Whether to encode array values only. If false,
964
     * both the array keys and array values will be encoded.
965
     * @param string|null $encoding The encoding to use, defaults to `ini_get('default_charset')`.
966
     *
967
     * @psalm-param array<mixed, mixed> $data
968
     *
969
     * @return array The encoded data.
970
     *
971
     * @link https://www.php.net/manual/en/function.htmlspecialchars.php
972
     */
973 1
    public static function htmlEncode(array $data, bool $valuesOnly = true, string $encoding = null): array
974
    {
975 1
        $d = [];
976
        /** @var mixed $value */
977 1
        foreach ($data as $key => $value) {
978 1
            if (!$valuesOnly && is_string($key)) {
979
                /** @psalm-suppress PossiblyNullArgument */
980 1
                $key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $encoding, true);
981
            }
982 1
            if (is_string($value)) {
983
                /** @psalm-suppress PossiblyNullArgument */
984 1
                $d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $encoding, true);
985 1
            } elseif (is_array($value)) {
986 1
                $d[$key] = static::htmlEncode($value, $valuesOnly, $encoding);
987
            } else {
988
                /** @var mixed */
989 1
                $d[$key] = $value;
990
            }
991
        }
992
993 1
        return $d;
994
    }
995
996
    /**
997
     * Decodes HTML entities into the corresponding characters in an array of strings.
998
     * Only array values will be decoded by default.
999
     * If a value is an array, this method will also decode it recursively.
1000
     * Only string values will be decoded.
1001
     *
1002
     * @param array $data Data to be decoded.
1003
     * @param bool $valuesOnly Whether to decode array values only. If false,
1004
     * both the array keys and array values will be decoded.
1005
     *
1006
     * @psalm-param array<mixed, mixed> $data
1007
     *
1008
     * @return array The decoded data.
1009
     *
1010
     * @link https://www.php.net/manual/en/function.htmlspecialchars-decode.php
1011
     */
1012 1
    public static function htmlDecode(array $data, bool $valuesOnly = true): array
1013
    {
1014 1
        $decoded = [];
1015
        /** @psalm-var mixed $value */
1016 1
        foreach ($data as $key => $value) {
1017 1
            if (!$valuesOnly && is_string($key)) {
1018 1
                $key = htmlspecialchars_decode($key, ENT_QUOTES);
1019
            }
1020 1
            if (is_string($value)) {
1021 1
                $decoded[$key] = htmlspecialchars_decode($value, ENT_QUOTES);
1022 1
            } elseif (is_array($value)) {
1023 1
                $decoded[$key] = static::htmlDecode($value);
1024
            } else {
1025
                /** @var mixed */
1026 1
                $decoded[$key] = $value;
1027
            }
1028
        }
1029
1030 1
        return $decoded;
1031
    }
1032
1033
    /**
1034
     * Returns a value indicating whether the given array is an associative array.
1035
     *
1036
     * An array is associative if all its keys are strings. If `$allStrings` is false,
1037
     * then an array will be treated as associative if at least one of its keys is a string.
1038
     *
1039
     * Note that an empty array will NOT be considered associative.
1040
     *
1041
     * @param array $array The array being checked.
1042
     * @param bool $allStrings Whether the array keys must be all strings in order for
1043
     * the array to be treated as associative.
1044
     *
1045
     * @return bool Whether the array is associative.
1046
     */
1047 1
    public static function isAssociative(array $array, bool $allStrings = true): bool
1048
    {
1049 1
        if ($array === []) {
1050 1
            return false;
1051
        }
1052
1053 1
        if ($allStrings) {
1054
            /** @psalm-suppress MixedAssignment */
1055 1
            foreach ($array as $key => $value) {
1056 1
                if (!is_string($key)) {
1057 1
                    return false;
1058
                }
1059
            }
1060
1061 1
            return true;
1062
        }
1063
1064
        /** @psalm-suppress MixedAssignment */
1065 1
        foreach ($array as $key => $value) {
1066 1
            if (is_string($key)) {
1067 1
                return true;
1068
            }
1069
        }
1070
1071 1
        return false;
1072
    }
1073
1074
    /**
1075
     * Returns a value indicating whether the given array is an indexed array.
1076
     *
1077
     * An array is indexed if all its keys are integers. If `$consecutive` is true,
1078
     * then the array keys must be a consecutive sequence starting from 0.
1079
     *
1080
     * Note that an empty array will be considered indexed.
1081
     *
1082
     * @param array $array The array being checked.
1083
     * @param bool $consecutive Whether the array keys must be a consecutive sequence
1084
     * in order for the array to be treated as indexed.
1085
     *
1086
     * @return bool Whether the array is indexed.
1087
     */
1088 1
    public static function isIndexed(array $array, bool $consecutive = false): bool
1089
    {
1090 1
        if ($array === []) {
1091 1
            return true;
1092
        }
1093
1094 1
        if ($consecutive) {
1095 1
            return array_keys($array) === range(0, count($array) - 1);
1096
        }
1097
1098
        /** @psalm-var mixed $value */
1099 1
        foreach ($array as $key => $value) {
1100 1
            if (!is_int($key)) {
1101 1
                return false;
1102
            }
1103
        }
1104
1105 1
        return true;
1106
    }
1107
1108
    /**
1109
     * Check whether an array or `\Traversable` contains an element.
1110
     *
1111
     * This method does the same as the PHP function {@see in_array()}
1112
     * but additionally works for objects that implement the {@see \Traversable} interface.
1113
     *
1114
     * @param mixed $needle The value to look for.
1115
     * @param iterable $haystack The set of values to search.
1116
     * @param bool $strict Whether to enable strict (`===`) comparison.
1117
     *
1118
     * @throws InvalidArgumentException if `$haystack` is neither traversable nor an array.
1119
     *
1120
     * @return bool `true` if `$needle` was found in `$haystack`, `false` otherwise.
1121
     *
1122
     * @link https://php.net/manual/en/function.in-array.php
1123
     */
1124 3
    public static function isIn($needle, iterable $haystack, bool $strict = false): bool
1125
    {
1126 3
        if (is_array($haystack)) {
1127 3
            return in_array($needle, $haystack, $strict);
1128
        }
1129
1130
        /** @psalm-var mixed $value */
1131 3
        foreach ($haystack as $value) {
1132 3
            if ($needle == $value && (!$strict || $needle === $value)) {
1133 3
                return true;
1134
            }
1135
        }
1136
1137 3
        return false;
1138
    }
1139
1140
    /**
1141
     * Checks whether an array or {@see \Traversable} is a subset of another array or {@see \Traversable}.
1142
     *
1143
     * This method will return `true`, if all elements of `$needles` are contained in
1144
     * `$haystack`. If at least one element is missing, `false` will be returned.
1145
     *
1146
     * @param iterable $needles The values that must **all** be in `$haystack`.
1147
     * @param iterable $haystack The set of value to search.
1148
     * @param bool $strict Whether to enable strict (`===`) comparison.
1149
     *
1150
     * @throws InvalidArgumentException if `$haystack` or `$needles` is neither traversable nor an array.
1151
     *
1152
     * @return bool `true` if `$needles` is a subset of `$haystack`, `false` otherwise.
1153
     */
1154 1
    public static function isSubset(iterable $needles, iterable $haystack, bool $strict = false): bool
1155
    {
1156
        /** @psalm-var mixed $needle */
1157 1
        foreach ($needles as $needle) {
1158 1
            if (!static::isIn($needle, $haystack, $strict)) {
1159 1
                return false;
1160
            }
1161
        }
1162
1163 1
        return true;
1164
    }
1165
1166
    /**
1167
     * Filters array according to rules specified.
1168
     *
1169
     * For example:
1170
     *
1171
     * ```php
1172
     * $array = [
1173
     *     'A' => [1, 2],
1174
     *     'B' => [
1175
     *         'C' => 1,
1176
     *         'D' => 2,
1177
     *     ],
1178
     *     'E' => 1,
1179
     * ];
1180
     *
1181
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['A']);
1182
     * // $result will be:
1183
     * // [
1184
     * //     'A' => [1, 2],
1185
     * // ]
1186
     *
1187
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['A', 'B.C']);
1188
     * // $result will be:
1189
     * // [
1190
     * //     'A' => [1, 2],
1191
     * //     'B' => ['C' => 1],
1192
     * // ]
1193
     *
1194
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['B', '!B.C']);
1195
     * // $result will be:
1196
     * // [
1197
     * //     'B' => ['D' => 2],
1198
     * // ]
1199
     * ```
1200
     *
1201
     * @param array $array Source array.
1202
     * @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...
1203
     * Each rule is:
1204
     * - `var` - `$array['var']` will be left in result.
1205
     * - `var.key` = only `$array['var']['key']` will be left in result.
1206
     * - `!var.key` = `$array['var']['key']` will be removed from result.
1207
     *
1208
     * @return array Filtered array.
1209
     */
1210 17
    public static function filter(array $array, array $filters): array
1211
    {
1212 17
        $result = [];
1213 17
        $excludeFilters = [];
1214
1215 17
        foreach ($filters as $filter) {
1216 17
            if ($filter[0] === '!') {
1217 6
                $excludeFilters[] = substr($filter, 1);
1218 6
                continue;
1219
            }
1220
1221 17
            $nodeValue = $array; // Set $array as root node.
1222 17
            $keys = explode('.', $filter);
1223 17
            foreach ($keys as $key) {
1224 17
                if (!is_array($nodeValue) || !array_key_exists($key, $nodeValue)) {
1225 4
                    continue 2; // Jump to next filter.
1226
                }
1227
                /** @var mixed */
1228 15
                $nodeValue = $nodeValue[$key];
1229
            }
1230
1231
            // We've found a value now let's insert it.
1232 13
            $resultNode = &$result;
1233 13
            foreach ($keys as $key) {
1234 13
                if (!array_key_exists($key, $resultNode)) {
1235 13
                    $resultNode[$key] = [];
1236
                }
1237 13
                $resultNode = &$resultNode[$key];
1238
            }
1239
            /** @var mixed */
1240 13
            $resultNode = $nodeValue;
1241
        }
1242
1243
        /** @var array $result */
1244
1245 17
        foreach ($excludeFilters as $filter) {
1246 6
            $excludeNode = &$result;
1247 6
            $keys = explode('.', $filter);
1248 6
            $numNestedKeys = count($keys) - 1;
1249 6
            foreach ($keys as $i => $key) {
1250 6
                if (!is_array($excludeNode) || !array_key_exists($key, $excludeNode)) {
1251 2
                    continue 2; // Jump to next filter.
1252
                }
1253
1254 5
                if ($i < $numNestedKeys) {
1255
                    /** @var mixed */
1256 5
                    $excludeNode = &$excludeNode[$key];
1257
                } else {
1258 4
                    unset($excludeNode[$key]);
1259 4
                    break;
1260
                }
1261
            }
1262
        }
1263
1264 17
        return $result;
1265
    }
1266
1267
    /**
1268
     * Returns the public member variables of an object.
1269
     *
1270
     * This method is provided such that we can get the public member variables of an object. It is different
1271
     * from {@see get_object_vars()} because the latter will return private and protected variables if it
1272
     * is called within the object itself.
1273
     *
1274
     * @param object $object The object to be handled.
1275
     *
1276
     * @return array|null The public member variables of the object or null if not object given.
1277
     *
1278
     * @link https://www.php.net/manual/en/function.get-object-vars.php
1279
     */
1280 4
    public static function getObjectVars(object $object): ?array
1281
    {
1282 4
        return get_object_vars($object);
1283
    }
1284
1285
    /**
1286
     * @param mixed $key
1287
     *
1288
     * @return string
1289
     */
1290 119
    private static function normalizeArrayKey($key): string
1291
    {
1292 119
        return is_float($key) ? NumericHelper::normalize($key) : (string)$key;
1293
    }
1294
}
1295