Passed
Push — master ( b923ab...fb82ac )
by Alexander
01:57
created

ArrayHelper::merge()   B

Complexity

Conditions 10
Paths 7

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 10

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 25
ccs 13
cts 13
cp 1
rs 7.6666
cc 10
nc 7
nop 1
crap 10

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

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