Passed
Pull Request — master (#121)
by Sergei
02:10
created

ArrayHelper   F

Complexity

Total Complexity 151

Size/Duplication

Total Lines 1277
Duplicated Lines 0 %

Test Coverage

Coverage 99.66%

Importance

Changes 14
Bugs 2 Features 0
Metric Value
wmc 151
eloc 270
c 14
b 2
f 0
dl 0
loc 1277
ccs 292
cts 293
cp 0.9966
rs 2

28 Methods

Rating   Name   Duplication   Size   Complexity  
C toArray() 0 55 15
B merge() 0 25 10
B getValue() 0 27 8
C filter() 0 55 13
A getExistsKeys() 0 11 2
B isAssociative() 0 23 7
A setValue() 0 23 6
A pathExists() 0 7 1
A isIn() 0 14 6
A getObjectVars() 0 3 1
A getValueByPath() 0 6 2
A isIndexed() 0 18 5
B index() 0 41 9
B htmlDecode() 0 25 7
A group() 0 3 1
A remove() 0 21 6
A keyExists() 0 19 6
A removeByPath() 0 3 1
A getColumn() 0 16 4
A rootKeyExists() 0 15 4
B htmlEncode() 0 25 7
B map() 0 26 7
A setValueByPath() 0 3 2
A removeValue() 0 13 3
A normalizeArrayKey() 0 3 2
A isSubset() 0 10 3
B getRootValue() 0 18 7
A parseMixedPath() 0 24 6

How to fix   Complexity   

Complex Class

Complex classes like ArrayHelper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ArrayHelper, and based on these observations, apply Extract Interface, too.

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

1297
                    $newPath = array_merge($newPath, /** @scrutinizer ignore-type */ $parsedPath);
Loading history...
1298 4
                    continue;
1299
                }
1300
1301 4
                $newPath[] = $key;
1302
            }
1303 17
            return $newPath;
1304
        }
1305
1306 70
        return is_string($path) ? StringHelper::parsePath($path, $delimiter) : $path;
1307
    }
1308
}
1309