Passed
Push — master ( 88b546...4877d3 )
by Alexander
03:34 queued 01:18
created

ArrayHelper::getValue()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 27
ccs 14
cts 14
cp 1
rs 8.4444
cc 8
nc 6
nop 3
crap 8
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|array<array-key,float|int|string>
27
 * @psalm-type ArrayPath = float|int|string|array<array-key,float|int|string|array<array-key,float|int|string>>
28
 */
29
final class ArrayHelper
30
{
31
    /**
32
     * Converts an object or an array of objects into an array.
33
     *
34
     * For example:
35
     *
36
     * ```php
37
     * [
38
     *     Post::class => [
39
     *         'id',
40
     *         'title',
41
     *         'createTime' => 'created_at',
42
     *         'length' => function ($post) {
43
     *             return strlen($post->content);
44
     *         },
45
     *     ],
46
     * ]
47
     * ```
48
     *
49
     * The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
50
     *
51
     * ```php
52
     * [
53
     *     'id' => 123,
54
     *     'title' => 'test',
55
     *     'createTime' => '2013-01-01 12:00AM',
56
     *     'length' => 301,
57
     * ]
58
     * ```
59
     *
60
     * @param 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 91
    public static function getValue($array, $key, $default = null)
206
    {
207 91
        if ($key instanceof Closure) {
208 16
            return $key($array, $default);
209
        }
210
211
        /** @psalm-suppress DocblockTypeContradiction */
212 83
        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 82
        if (is_array($key)) {
219
            /** @psalm-var array<mixed,string|int> $key */
220 38
            $lastKey = array_pop($key);
221 38
            foreach ($key as $keyPart) {
222
                /** @var mixed */
223 35
                $array = self::getRootValue($array, $keyPart, null);
224 35
                if (!is_array($array) && !is_object($array)) {
225 9
                    return $default;
226
                }
227
            }
228 30
            return self::getRootValue($array, $lastKey, $default);
229
        }
230
231 46
        return self::getRootValue($array, $key, $default);
232
    }
233
234
    /**
235
     * @param mixed $array Array or object to extract value from, otherwise method will return $default.
236
     * @param float|int|string $key Key name of the array element or property name of the object.
237
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
238
     * getting value from an object.
239
     *
240
     * @return mixed The value of the element if found, default value otherwise.
241
     */
242 109
    private static function getRootValue($array, $key, $default)
243
    {
244 109
        if (is_array($array)) {
245 97
            $key = self::normalizeArrayKey($key);
246 97
            return array_key_exists($key, $array) ? $array[$key] : $default;
247
        }
248
249 14
        if (is_object($array)) {
250
            try {
251 14
                return $array::$$key;
252 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...
253
                // This is expected to fail if the property does not exist, or __get() is not implemented.
254
                // It is not reliably possible to check whether a property is accessible beforehand.
255 14
                return $array->$key;
256
            }
257
        }
258
259
        return $default;
260
    }
261
262
    /**
263
     * Retrieves the value of an array element or object property with the given key or property name.
264
     * If the key does not exist in the array or object, the default value will be returned instead.
265
     *
266
     * The key may be specified in a dot-separated format to retrieve the value of a sub-array or the property
267
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
268
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
269
     * or `$array->x` is neither an array nor an object, the default value will be returned.
270
     * Note that if the array already has an element `x.y.z`, then its value will be returned
271
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
272
     * like `['x', 'y', 'z']`.
273
     *
274
     * Below are some usage examples,
275
     *
276
     * ```php
277
     * // Using separated format to retrieve the property of embedded object:
278
     * $street = \Yiisoft\Arrays\ArrayHelper::getValue($users, 'address.street');
279
     *
280
     * // Using an array of keys to retrieve the value:
281
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
282
     * ```
283
     *
284
     * @param array|object $array Array or object to extract value from.
285
     * @param array|Closure|float|int|string $path Key name of the array element, an array of keys or property name
286
     * of the object, or an anonymous function returning the value. The anonymous function signature should be:
287
     * `function($array, $defaultValue)`.
288
     * @param mixed $default The default value to be returned if the specified array key does not exist. Not used when
289
     * getting value from an object.
290
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
291
     * to "." (dot).
292
     *
293
     * @psalm-param ArrayPath|Closure $path
294
     *
295
     * @return mixed The value of the element if found, default value otherwise.
296
     */
297 33
    public static function getValueByPath($array, $path, $default = null, string $delimiter = '.')
298
    {
299 33
        return self::getValue(
300 33
            $array,
301 33
            $path instanceof Closure ? $path : self::parsePath($path, $delimiter),
302 33
            $default
303
        );
304
    }
305
306
    /**
307
     * Writes a value into an associative array at the key path specified.
308
     * If there is no such key path yet, it will be created recursively.
309
     * If the key exists, it will be overwritten.
310
     *
311
     * ```php
312
     *  $array = [
313
     *      'key' => [
314
     *          'in' => [
315
     *              'val1',
316
     *              'key' => 'val'
317
     *          ]
318
     *      ]
319
     *  ];
320
     * ```
321
     *
322
     * The result of `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
323
     * will be the following:
324
     *
325
     * ```php
326
     *  [
327
     *      'key' => [
328
     *          'in' => [
329
     *              'arr' => 'val'
330
     *          ]
331
     *      ]
332
     *  ]
333
     * ```
334
     *
335
     * @param array $array The array to write the value to.
336
     * @param array|float|int|string|null $key The path of where do you want to write a value to `$array`
337
     * the path can be described by an array of keys. If the path is null then `$array` will be assigned the `$value`.
338
     *
339
     * @psalm-param ArrayKey|null $key
340
     *
341
     * @param mixed $value The value to be written.
342
     */
343 29
    public static function setValue(array &$array, $key, $value): void
344
    {
345 29
        if ($key === null) {
346
            /** @var mixed */
347 2
            $array = $value;
348 2
            return;
349
        }
350
351 27
        $keys = is_array($key) ? $key : [$key];
352
353 27
        while (count($keys) > 1) {
354 15
            $k = self::normalizeArrayKey(array_shift($keys));
355 15
            if (!isset($array[$k])) {
356 8
                $array[$k] = [];
357
            }
358 15
            if (!is_array($array[$k])) {
359 2
                $array[$k] = [$array[$k]];
360
            }
361 15
            $array = &$array[$k];
362
        }
363
364
        /** @var mixed */
365 27
        $array[self::normalizeArrayKey(array_shift($keys))] = $value;
366 27
    }
367
368
    /**
369
     * Writes a value into an associative array at the key path specified.
370
     * If there is no such key path yet, it will be created recursively.
371
     * If the key exists, it will be overwritten.
372
     *
373
     * ```php
374
     *  $array = [
375
     *      'key' => [
376
     *          'in' => [
377
     *              'val1',
378
     *              'key' => 'val'
379
     *          ]
380
     *      ]
381
     *  ];
382
     * ```
383
     *
384
     * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
385
     *
386
     * ```php
387
     *  [
388
     *      'key' => [
389
     *          'in' => [
390
     *              ['arr' => 'val'],
391
     *              'key' => 'val'
392
     *          ]
393
     *      ]
394
     *  ]
395
     *
396
     * ```
397
     *
398
     * The result of
399
     * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
400
     * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
401
     * will be the following:
402
     *
403
     * ```php
404
     *  [
405
     *      'key' => [
406
     *          'in' => [
407
     *              'arr' => 'val'
408
     *          ]
409
     *      ]
410
     *  ]
411
     * ```
412
     *
413
     * @param array $array The array to write the value to.
414
     * @param array|float|int|string|null $path The path of where do you want to write a value to `$array`.
415
     * The path can be described by a string when each key should be separated by a dot.
416
     * You can also describe the path as an array of keys. If the path is null then `$array` will be assigned
417
     * the `$value`.
418
     * @param mixed $value The value to be written.
419
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
420
     * to "." (dot).
421
     *
422
     * @psalm-param ArrayPath|null $path
423
     */
424 21
    public static function setValueByPath(array &$array, $path, $value, string $delimiter = '.'): void
425
    {
426 21
        self::setValue($array, $path === null ? null : self::parsePath($path, $delimiter), $value);
427 21
    }
428
429
    /**
430
     * @param array|float|int|string $path The path of where do you want to write a value to `$array`.
431
     * The path can be described by a string when each key should be separated by delimiter.
432
     * You can also describe the path as an array of keys.
433
     * @param string $delimiter A separator, used to parse string $key for embedded object property retrieving. Defaults
434
     * to "." (dot).
435
     *
436
     * @psalm-param ArrayPath $path
437
     *
438
     * @return array|float|int|string
439
     * @psalm-return ArrayKey
440
     */
441 82
    private static function parsePath($path, string $delimiter)
442
    {
443 82
        if (is_string($path)) {
444 77
            return explode($delimiter, $path);
445
        }
446 22
        if (is_array($path)) {
447 17
            $newPath = [];
448 17
            foreach ($path as $key) {
449 17
                if (is_string($key) || is_array($key)) {
450
                    /** @var list<float|int|string> $parsedPath */
451 17
                    $parsedPath = self::parsePath($key, $delimiter);
452 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

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