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

ArrayHelper::merge()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

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