Passed
Pull Request — master (#84)
by Sergei
01:51
created

ArrayHelper::filter()   C

Complexity

Conditions 13
Paths 45

Size

Total Lines 55
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 31
CRAP Score 13

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 31
c 1
b 0
f 0
dl 0
loc 55
ccs 31
cts 31
cp 1
rs 6.6166
cc 13
nc 45
nop 2
crap 13

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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

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

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