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

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