Passed
Push — master ( 32bc4a...e3a929 )
by Alexander
01:53
created

ArrayHelper   F

Complexity

Total Complexity 160

Size/Duplication

Total Lines 1278
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 11
Bugs 0 Features 0
Metric Value
wmc 160
eloc 281
c 11
b 0
f 0
dl 0
loc 1278
ccs 301
cts 301
cp 1
rs 2

30 Methods

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

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