Passed
Pull Request — master (#121)
by Sergei
06:46 queued 04:07
created

ArrayHelper::getRootValue()   B

Complexity

Conditions 11
Paths 4

Size

Total Lines 39
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 11.055

Importance

Changes 0
Metric Value
eloc 25
c 0
b 0
f 0
dl 0
loc 39
ccs 24
cts 26
cp 0.9231
rs 7.3166
cc 11
nc 4
nop 3
crap 11.055

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1318
                    $newPath = array_merge($newPath, /** @scrutinizer ignore-type */ $parsedPath);
Loading history...
1319 4
                    continue;
1320
                }
1321
1322 4
                $newPath[] = $key;
1323
            }
1324 17
            return $newPath;
1325
        }
1326
1327 70
        return is_string($path) ? StringHelper::parsePath($path, $delimiter) : $path;
1328
    }
1329
}
1330