Passed
Pull Request — master (#97)
by Sergei
02:33
created

ArrayHelper::map()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7

Importance

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

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