Passed
Pull Request — 2.2 (#20357)
by Wilmer
13:33 queued 05:55
created

BaseArrayHelper::isSubset()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 6
c 0
b 0
f 0
nc 4
nop 3
dl 0
loc 13
ccs 7
cts 7
cp 1
crap 4
rs 10
1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\helpers;
10
11
use Yii;
12
use ArrayAccess;
13
use Traversable;
14
use yii\base\Arrayable;
15
use yii\base\InvalidArgumentException;
16
17
/**
18
 * BaseArrayHelper provides concrete implementation for [[ArrayHelper]].
19
 *
20
 * Do not use BaseArrayHelper. Use [[ArrayHelper]] instead.
21
 *
22
 * @author Qiang Xue <[email protected]>
23
 * @since 2.0
24
 */
25
class BaseArrayHelper
26
{
27
    /**
28
     * Converts an object or an array of objects into an array.
29
     * @param object|array|string $object the object to be converted into an array
30
     * @param array $properties a mapping from object class names to the properties that need to put into the resulting arrays.
31
     * The properties specified for each class is an array of the following format:
32
     *
33
     * ```php
34
     * [
35
     *     'app\models\Post' => [
36
     *         'id',
37
     *         'title',
38
     *         // the key name in array result => property name
39
     *         'createTime' => 'created_at',
40
     *         // the key name in array result => anonymous function
41
     *         'length' => function ($post) {
42
     *             return strlen($post->content);
43
     *         },
44
     *     ],
45
     * ]
46
     * ```
47
     *
48
     * The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
49
     *
50
     * ```php
51
     * [
52
     *     'id' => 123,
53
     *     'title' => 'test',
54
     *     'createTime' => '2013-01-01 12:00AM',
55
     *     'length' => 301,
56
     * ]
57
     * ```
58
     *
59
     * @param bool $recursive whether to recursively converts properties which are objects into arrays.
60
     * @return array the array representation of the object
61
     */
62 24
    public static function toArray($object, $properties = [], $recursive = true)
63
    {
64 24
        if (is_array($object)) {
65 24
            if ($recursive) {
66 24
                foreach ($object as $key => $value) {
67 24
                    if (is_array($value) || is_object($value)) {
68 4
                        $object[$key] = static::toArray($value, $properties, true);
69
                    }
70
                }
71
            }
72
73 24
            return $object;
74 8
        } elseif ($object instanceof \DateTimeInterface) {
75 1
            return (array)$object;
76 8
        } elseif (is_object($object)) {
77 8
            if (!empty($properties)) {
78 1
                $className = get_class($object);
79 1
                if (!empty($properties[$className])) {
80 1
                    $result = [];
81 1
                    foreach ($properties[$className] as $key => $name) {
82 1
                        if (is_int($key)) {
83 1
                            $result[$name] = $object->$name;
84
                        } else {
85 1
                            $result[$key] = static::getValue($object, $name);
86
                        }
87
                    }
88
89 1
                    return $recursive ? static::toArray($result, $properties) : $result;
90
                }
91
            }
92 8
            if ($object instanceof Arrayable) {
93 1
                $result = $object->toArray([], [], $recursive);
94
            } else {
95 8
                $result = [];
96 8
                foreach ($object as $key => $value) {
97 8
                    $result[$key] = $value;
98
                }
99
            }
100
101 8
            return $recursive ? static::toArray($result, $properties) : $result;
102
        }
103
104 1
        return [$object];
105
    }
106
107
    /**
108
     * Merges two or more arrays into one recursively.
109
     * If each array has an element with the same string key value, the latter
110
     * will overwrite the former (different from array_merge_recursive).
111
     * Recursive merging will be conducted if both arrays have an element of array
112
     * type and are having the same key.
113
     * For integer-keyed elements, the elements from the latter array will
114
     * be appended to the former array.
115
     * You can use [[UnsetArrayValue]] object to unset value from previous array or
116
     * [[ReplaceArrayValue]] to force replace former value instead of recursive merging.
117
     * @param array $a array to be merged to
118
     * @param array $b array to be merged from. You can specify additional
119
     * arrays via third argument, fourth argument etc.
120
     * @return array the merged array (the original arrays are not changed.)
121
     */
122 2232
    public static function merge($a, $b)
123
    {
124 2232
        $args = func_get_args();
125 2232
        $res = array_shift($args);
126 2232
        while (!empty($args)) {
127 2232
            foreach (array_shift($args) as $k => $v) {
128 1418
                if ($v instanceof UnsetArrayValue) {
129 1
                    unset($res[$k]);
130 1418
                } elseif ($v instanceof ReplaceArrayValue) {
131 1
                    $res[$k] = $v->value;
132 1418
                } elseif (is_int($k)) {
133 5
                    if (array_key_exists($k, $res)) {
134 5
                        $res[] = $v;
135
                    } else {
136 5
                        $res[$k] = $v;
137
                    }
138 1416
                } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
139 265
                    $res[$k] = static::merge($res[$k], $v);
140
                } else {
141 1416
                    $res[$k] = $v;
142
                }
143
            }
144
        }
145
146 2232
        return $res;
147
    }
148
149
    /**
150
     * Retrieves the value of an array element or object property with the given key or property name.
151
     * If the key does not exist in the array, the default value will be returned instead.
152
     * Not used when getting value from an object.
153
     *
154
     * The key may be specified in a dot format to retrieve the value of a sub-array or the property
155
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
156
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
157
     * or `$array->x` is neither an array nor an object, the default value will be returned.
158
     * Note that if the array already has an element `x.y.z`, then its value will be returned
159
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
160
     * like `['x', 'y', 'z']`.
161
     *
162
     * Below are some usage examples,
163
     *
164
     * ```php
165
     * // working with array
166
     * $username = \yii\helpers\ArrayHelper::getValue($_POST, 'username');
167
     * // working with object
168
     * $username = \yii\helpers\ArrayHelper::getValue($user, 'username');
169
     * // working with anonymous function
170
     * $fullName = \yii\helpers\ArrayHelper::getValue($user, function ($user, $defaultValue) {
171
     *     return $user->firstName . ' ' . $user->lastName;
172
     * });
173
     * // using dot format to retrieve the property of embedded object
174
     * $street = \yii\helpers\ArrayHelper::getValue($users, 'address.street');
175
     * // using an array of keys to retrieve the value
176
     * $value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']);
177
     * ```
178
     *
179
     * @param array|object $array array or object to extract value from
180
     * @param string|\Closure|array $key key name of the array element, an array of keys or property name of the object,
181
     * or an anonymous function returning the value. The anonymous function signature should be:
182
     * `function($array, $defaultValue)`.
183
     * The possibility to pass an array of keys is available since version 2.0.4.
184
     * @param mixed $default the default value to be returned if the specified array key does not exist. Not used when
185
     * getting value from an object.
186
     * @return mixed the value of the element if found, default value otherwise
187
     */
188 135
    public static function getValue($array, $key, $default = null)
189
    {
190 135
        if ($key instanceof \Closure) {
191 7
            return $key($array, $default);
192
        }
193
194 133
        if (is_array($key)) {
195 2
            $lastKey = array_pop($key);
196 2
            foreach ($key as $keyPart) {
197 2
                $array = static::getValue($array, $keyPart);
198
            }
199 2
            $key = $lastKey;
200
        }
201
202 133
        if (is_object($array) && property_exists($array, $key)) {
203 11
            return $array->$key;
204
        }
205
206 126
        if (static::keyExists($key, $array)) {
207 87
            return $array[$key];
208
        }
209
210 69
        if ($key && ($pos = strrpos($key, '.')) !== false) {
211 15
            $array = static::getValue($array, substr($key, 0, $pos), $default);
212 15
            $key = substr($key, $pos + 1);
213
        }
214
215 69
        if (static::keyExists($key, $array)) {
216 13
            return $array[$key];
217
        }
218 62
        if (is_object($array)) {
219
            // this is expected to fail if the property does not exist, or __get() is not implemented
220
            // it is not reliably possible to check whether a property is accessible beforehand
221
            try {
222 5
                return $array->$key;
223 3
            } catch (\Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $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...
224 3
                if ($array instanceof ArrayAccess) {
225 2
                    return $default;
226
                }
227 1
                throw $e;
228
            }
229
        }
230
231 58
        return $default;
232
    }
233
234
    /**
235
     * Writes a value into an associative array at the key path specified.
236
     * If there is no such key path yet, it will be created recursively.
237
     * If the key exists, it will be overwritten.
238
     *
239
     * ```php
240
     *  $array = [
241
     *      'key' => [
242
     *          'in' => [
243
     *              'val1',
244
     *              'key' => 'val'
245
     *          ]
246
     *      ]
247
     *  ];
248
     * ```
249
     *
250
     * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
251
     *
252
     * ```php
253
     *  [
254
     *      'key' => [
255
     *          'in' => [
256
     *              ['arr' => 'val'],
257
     *              'key' => 'val'
258
     *          ]
259
     *      ]
260
     *  ]
261
     *
262
     * ```
263
     *
264
     * The result of
265
     * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
266
     * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
267
     * will be the following:
268
     *
269
     * ```php
270
     *  [
271
     *      'key' => [
272
     *          'in' => [
273
     *              'arr' => 'val'
274
     *          ]
275
     *      ]
276
     *  ]
277
     * ```
278
     *
279
     * @param array $array the array to write the value to
280
     * @param string|array|null $path the path of where do you want to write a value to `$array`
281
     * the path can be described by a string when each key should be separated by a dot
282
     * you can also describe the path as an array of keys
283
     * if the path is null then `$array` will be assigned the `$value`
284
     * @param mixed $value the value to be written
285
     * @since 2.0.13
286
     */
287 17
    public static function setValue(&$array, $path, $value)
288
    {
289 17
        if ($path === null) {
290 1
            $array = $value;
291 1
            return;
292
        }
293
294 16
        $keys = is_array($path) ? $path : explode('.', $path);
295
296 16
        while (count($keys) > 1) {
297 13
            $key = array_shift($keys);
298 13
            if (!isset($array[$key])) {
299 4
                $array[$key] = [];
300
            }
301 13
            if (!is_array($array[$key])) {
302 2
                $array[$key] = [$array[$key]];
303
            }
304 13
            $array = &$array[$key];
305
        }
306
307 16
        $array[array_shift($keys)] = $value;
308
    }
309
310
    /**
311
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
312
     * will be returned instead.
313
     *
314
     * Usage examples,
315
     *
316
     * ```php
317
     * // $array = ['type' => 'A', 'options' => [1, 2]];
318
     * // working with array
319
     * $type = \yii\helpers\ArrayHelper::remove($array, 'type');
320
     * // $array content
321
     * // $array = ['options' => [1, 2]];
322
     * ```
323
     *
324
     * @param array $array the array to extract value from
325
     * @param string $key key name of the array element
326
     * @param mixed $default the default value to be returned if the specified key does not exist
327
     * @return mixed|null the value of the element if found, default value otherwise
328
     */
329 245
    public static function remove(&$array, $key, $default = null)
330
    {
331
        // ToDo: This check can be removed when the minimum PHP version is >= 8.1 (Yii2.2)
332 245
        if (is_float($key)) {
0 ignored issues
show
introduced by
The condition is_float($key) is always false.
Loading history...
333
            $key = (int)$key;
334
        }
335
336 245
        if (is_array($array) && array_key_exists($key, $array)) {
337 56
            $value = $array[$key];
338 56
            unset($array[$key]);
339
340 56
            return $value;
341
        }
342
343 237
        return $default;
344
    }
345
346
    /**
347
     * Removes items with matching values from the array and returns the removed items.
348
     *
349
     * Example,
350
     *
351
     * ```php
352
     * $array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
353
     * $removed = \yii\helpers\ArrayHelper::removeValue($array, 'Jackson');
354
     * // result:
355
     * // $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
356
     * // $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
357
     * ```
358
     *
359
     * @param array $array the array where to look the value from
360
     * @param mixed $value the value to remove from the array
361
     * @return array the items that were removed from the array
362
     * @since 2.0.11
363
     */
364 2
    public static function removeValue(&$array, $value)
365
    {
366 2
        $result = [];
367 2
        if (is_array($array)) {
0 ignored issues
show
introduced by
The condition is_array($array) is always true.
Loading history...
368 2
            foreach ($array as $key => $val) {
369 2
                if ($val === $value) {
370 1
                    $result[$key] = $val;
371 1
                    unset($array[$key]);
372
                }
373
            }
374
        }
375
376 2
        return $result;
377
    }
378
379
    /**
380
     * Indexes and/or groups the array according to a specified key.
381
     * The input should be either multidimensional array or an array of objects.
382
     *
383
     * The $key can be either a key name of the sub-array, a property name of object, or an anonymous
384
     * function that must return the value that will be used as a key.
385
     *
386
     * $groups is an array of keys, that will be used to group the input array into one or more sub-arrays based
387
     * on keys specified.
388
     *
389
     * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
390
     * to `$groups` not specified then the element is discarded.
391
     *
392
     * For example:
393
     *
394
     * ```php
395
     * $array = [
396
     *     ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
397
     *     ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
398
     *     ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
399
     * ];
400
     * $result = ArrayHelper::index($array, 'id');
401
     * ```
402
     *
403
     * The result will be an associative array, where the key is the value of `id` attribute
404
     *
405
     * ```php
406
     * [
407
     *     '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
408
     *     '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
409
     *     // The second element of an original array is overwritten by the last element because of the same id
410
     * ]
411
     * ```
412
     *
413
     * An anonymous function can be used in the grouping array as well.
414
     *
415
     * ```php
416
     * $result = ArrayHelper::index($array, function ($element) {
417
     *     return $element['id'];
418
     * });
419
     * ```
420
     *
421
     * Passing `id` as a third argument will group `$array` by `id`:
422
     *
423
     * ```php
424
     * $result = ArrayHelper::index($array, null, 'id');
425
     * ```
426
     *
427
     * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
428
     * and indexed by `data` on the third level:
429
     *
430
     * ```php
431
     * [
432
     *     '123' => [
433
     *         ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
434
     *     ],
435
     *     '345' => [ // all elements with this index are present in the result array
436
     *         ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
437
     *         ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
438
     *     ]
439
     * ]
440
     * ```
441
     *
442
     * The anonymous function can be used in the array of grouping keys as well:
443
     *
444
     * ```php
445
     * $result = ArrayHelper::index($array, 'data', [function ($element) {
446
     *     return $element['id'];
447
     * }, 'device']);
448
     * ```
449
     *
450
     * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
451
     * and indexed by the `data` on the third level:
452
     *
453
     * ```php
454
     * [
455
     *     '123' => [
456
     *         'laptop' => [
457
     *             'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
458
     *         ]
459
     *     ],
460
     *     '345' => [
461
     *         'tablet' => [
462
     *             'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
463
     *         ],
464
     *         'smartphone' => [
465
     *             'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
466
     *         ]
467
     *     ]
468
     * ]
469
     * ```
470
     *
471
     * @param array $array the array that needs to be indexed or grouped
472
     * @param string|\Closure|null $key the column name or anonymous function which result will be used to index the array
473
     * @param string|string[]|\Closure[]|null $groups the array of keys, that will be used to group the input array
474
     * by one or more keys. If the $key attribute or its value for the particular element is null and $groups is not
475
     * defined, the array element will be discarded. Otherwise, if $groups is specified, array element will be added
476
     * to the result array without any key. This parameter is available since version 2.0.8.
477
     * @return array the indexed and/or grouped array
478
     */
479 3
    public static function index($array, $key, $groups = [])
480
    {
481 3
        $result = [];
482 3
        $groups = (array) $groups;
483
484 3
        foreach ($array as $element) {
485 3
            $lastArray = &$result;
486
487 3
            foreach ($groups as $group) {
488 1
                $value = static::getValue($element, $group);
489 1
                if (!array_key_exists($value, $lastArray)) {
490 1
                    $lastArray[$value] = [];
491
                }
492 1
                $lastArray = &$lastArray[$value];
493
            }
494
495 3
            if ($key === null) {
496 2
                if (!empty($groups)) {
497 2
                    $lastArray[] = $element;
498
                }
499
            } else {
500 3
                $value = static::getValue($element, $key);
501 3
                if ($value !== null) {
502 3
                    if (is_float($value)) {
503 1
                        $value = StringHelper::floatToString($value);
504
                    }
505 3
                    $lastArray[$value] = $element;
506
                }
507
            }
508 3
            unset($lastArray);
509
        }
510
511 3
        return $result;
512
    }
513
514
    /**
515
     * Returns the values of a specified column in an array.
516
     * The input array should be multidimensional or an array of objects.
517
     *
518
     * For example,
519
     *
520
     * ```php
521
     * $array = [
522
     *     ['id' => '123', 'data' => 'abc'],
523
     *     ['id' => '345', 'data' => 'def'],
524
     * ];
525
     * $result = ArrayHelper::getColumn($array, 'id');
526
     * // the result is: ['123', '345']
527
     *
528
     * // using anonymous function
529
     * $result = ArrayHelper::getColumn($array, function ($element) {
530
     *     return $element['id'];
531
     * });
532
     * ```
533
     *
534
     * @param array $array
535
     * @param int|string|array|\Closure $name
536
     * @param bool $keepKeys whether to maintain the array keys. If false, the resulting array
537
     * will be re-indexed with integers.
538
     * @return array the list of column values
539
     */
540 36
    public static function getColumn($array, $name, $keepKeys = true)
541
    {
542 36
        $result = [];
543 36
        if ($keepKeys) {
544 36
            foreach ($array as $k => $element) {
545 35
                $result[$k] = static::getValue($element, $name);
546
            }
547
        } else {
548 1
            foreach ($array as $element) {
549 1
                $result[] = static::getValue($element, $name);
550
            }
551
        }
552
553 36
        return $result;
554
    }
555
556
    /**
557
     * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
558
     * The `$from` and `$to` parameters specify the key names or property names to set up the map.
559
     * Optionally, one can further group the map according to a grouping field `$group`.
560
     *
561
     * For example,
562
     *
563
     * ```php
564
     * $array = [
565
     *     ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
566
     *     ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
567
     *     ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
568
     * ];
569
     *
570
     * $result = ArrayHelper::map($array, 'id', 'name');
571
     * // the result is:
572
     * // [
573
     * //     '123' => 'aaa',
574
     * //     '124' => 'bbb',
575
     * //     '345' => 'ccc',
576
     * // ]
577
     *
578
     * $result = ArrayHelper::map($array, 'id', 'name', 'class');
579
     * // the result is:
580
     * // [
581
     * //     'x' => [
582
     * //         '123' => 'aaa',
583
     * //         '124' => 'bbb',
584
     * //     ],
585
     * //     'y' => [
586
     * //         '345' => 'ccc',
587
     * //     ],
588
     * // ]
589
     * ```
590
     *
591
     * @param array $array
592
     * @param string|\Closure $from
593
     * @param string|\Closure $to
594
     * @param string|\Closure|null $group
595
     * @return array
596
     */
597 1
    public static function map($array, $from, $to, $group = null)
598
    {
599 1
        if (is_string($from) && is_string($to) && $group === null && strpos($from, '.') === false && strpos($to, '.') === false) {
600 1
            return array_column($array, $to, $from);
601
        }
602 1
        $result = [];
603 1
        foreach ($array as $element) {
604 1
            $key = static::getValue($element, $from);
605 1
            $value = static::getValue($element, $to);
606 1
            if ($group !== null) {
607 1
                $result[static::getValue($element, $group)][$key] = $value;
608
            } else {
609 1
                $result[$key] = $value;
610
            }
611
        }
612
613 1
        return $result;
614
    }
615
616
    /**
617
     * Checks if the given array contains the specified key.
618
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
619
     * key comparison.
620
     * @param string|int $key the key to check
621
     * @param array|ArrayAccess $array the array with keys to check
622
     * @param bool $caseSensitive whether the key comparison should be case-sensitive
623
     * @return bool whether the array contains the specified key
624
     */
625 146
    public static function keyExists($key, $array, $caseSensitive = true)
626
    {
627
        // ToDo: This check can be removed when the minimum PHP version is >= 8.1 (Yii2.2)
628 146
        if (is_float($key)) {
0 ignored issues
show
introduced by
The condition is_float($key) is always false.
Loading history...
629
            $key = (int)$key;
630
        }
631
632 146
        if ($caseSensitive) {
633 145
            if (is_array($array) && array_key_exists($key, $array)) {
634 78
                return true;
635
            }
636
            // Cannot use `array_has_key` on Objects for PHP 7.4+, therefore we need to check using [[ArrayAccess::offsetExists()]]
637 96
            return $array instanceof ArrayAccess && $array->offsetExists($key);
638
        }
639
640 2
        if ($array instanceof ArrayAccess) {
641 1
            throw new InvalidArgumentException('Second parameter($array) cannot be ArrayAccess in case insensitive mode');
642
        }
643
644 1
        foreach (array_keys($array) as $k) {
645 1
            if (strcasecmp($key, $k) === 0) {
646 1
                return true;
647
            }
648
        }
649
650 1
        return false;
651
    }
652
653
    /**
654
     * Sorts an array of objects or arrays (with the same structure) by one or several keys.
655
     * @param array $array the array to be sorted. The array will be modified after calling this method.
656
     * @param string|\Closure|array $key the key(s) to be sorted by. This refers to a key name of the sub-array
657
     * elements, a property name of the objects, or an anonymous function returning the values for comparison
658
     * purpose. The anonymous function signature should be: `function($item)`.
659
     * To sort by multiple keys, provide an array of keys here.
660
     * @param int|array $direction the sorting direction. It can be either `SORT_ASC` or `SORT_DESC`.
661
     * When sorting by multiple keys with different sorting directions, use an array of sorting directions.
662
     * @param int|array $sortFlag the PHP sort flag. Valid values include
663
     * `SORT_REGULAR`, `SORT_NUMERIC`, `SORT_STRING`, `SORT_LOCALE_STRING`, `SORT_NATURAL` and `SORT_FLAG_CASE`.
664
     * Please refer to [PHP manual](https://www.php.net/manual/en/function.sort.php)
665
     * for more details. When sorting by multiple keys with different sort flags, use an array of sort flags.
666
     * @throws InvalidArgumentException if the $direction or $sortFlag parameters do not have
667
     * correct number of elements as that of $key.
668
     */
669 10
    public static function multisort(&$array, $key, $direction = SORT_ASC, $sortFlag = SORT_REGULAR)
670
    {
671 10
        $keys = is_array($key) ? $key : [$key];
672 10
        if (empty($keys) || empty($array)) {
673 1
            return;
674
        }
675 10
        $n = count($keys);
676 10
        if (is_scalar($direction)) {
677 3
            $direction = array_fill(0, $n, $direction);
678 7
        } elseif (count($direction) !== $n) {
679 1
            throw new InvalidArgumentException('The length of $direction parameter must be the same as that of $keys.');
680
        }
681 9
        if (is_scalar($sortFlag)) {
682 8
            $sortFlag = array_fill(0, $n, $sortFlag);
683 2
        } elseif (count($sortFlag) !== $n) {
684 1
            throw new InvalidArgumentException('The length of $sortFlag parameter must be the same as that of $keys.');
685
        }
686 8
        $args = [];
687 8
        foreach ($keys as $i => $k) {
688 8
            $flag = $sortFlag[$i];
689 8
            $args[] = static::getColumn($array, $k);
690 8
            $args[] = $direction[$i];
691 8
            $args[] = $flag;
692
        }
693
694
        // This fix is used for cases when main sorting specified by columns has equal values
695
        // Without it it will lead to Fatal Error: Nesting level too deep - recursive dependency?
696 8
        $args[] = range(1, count($array));
697 8
        $args[] = SORT_ASC;
698 8
        $args[] = SORT_NUMERIC;
699
700 8
        $args[] = &$array;
701 8
        call_user_func_array('array_multisort', $args);
702
    }
703
704
    /**
705
     * Encodes special characters in an array of strings into HTML entities.
706
     * Only array values will be encoded by default.
707
     * If a value is an array, this method will also encode it recursively.
708
     * Only string values will be encoded.
709
     * @param array $data data to be encoded
710
     * @param bool $valuesOnly whether to encode array values only. If false,
711
     * both the array keys and array values will be encoded.
712
     * @param string|null $charset the charset that the data is using. If not set,
713
     * [[\yii\base\Application::charset]] will be used.
714
     * @return array the encoded data
715
     * @see https://www.php.net/manual/en/function.htmlspecialchars.php
716
     */
717 1
    public static function htmlEncode($data, $valuesOnly = true, $charset = null)
718
    {
719 1
        if ($charset === null) {
720 1
            $charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
721
        }
722 1
        $d = [];
723 1
        foreach ($data as $key => $value) {
724 1
            if (!$valuesOnly && is_string($key)) {
725 1
                $key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
726
            }
727 1
            if (is_string($value)) {
728 1
                $d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
729 1
            } elseif (is_array($value)) {
730 1
                $d[$key] = static::htmlEncode($value, $valuesOnly, $charset);
731
            } else {
732 1
                $d[$key] = $value;
733
            }
734
        }
735
736 1
        return $d;
737
    }
738
739
    /**
740
     * Decodes HTML entities into the corresponding characters in an array of strings.
741
     *
742
     * Only array values will be decoded by default.
743
     * If a value is an array, this method will also decode it recursively.
744
     * Only string values will be decoded.
745
     *
746
     * @param array $data data to be decoded
747
     * @param bool $valuesOnly whether to decode array values only. If `false`,
748
     * then both the array keys and array values will be decoded.
749
     * @return array the decoded data
750
     * @see https://www.php.net/manual/en/function.htmlspecialchars-decode.php
751
     */
752 1
    public static function htmlDecode($data, $valuesOnly = true)
753
    {
754 1
        $d = [];
755 1
        foreach ($data as $key => $value) {
756 1
            if (!$valuesOnly && is_string($key)) {
757 1
                $key = htmlspecialchars_decode($key, ENT_QUOTES | ENT_SUBSTITUTE);
758
            }
759 1
            if (is_string($value)) {
760 1
                $d[$key] = htmlspecialchars_decode($value, ENT_QUOTES | ENT_SUBSTITUTE);
761 1
            } elseif (is_array($value)) {
762 1
                $d[$key] = static::htmlDecode($value, $valuesOnly);
763
            } else {
764 1
                $d[$key] = $value;
765
            }
766
        }
767
768 1
        return $d;
769
    }
770
771
    /**
772
     * Returns a value indicating whether the given array is an associative array.
773
     *
774
     * An array is associative if all its keys are strings. If `$allStrings` is false,
775
     * then an array will be treated as associative if at least one of its keys is a string.
776
     *
777
     * Note that an empty array will NOT be considered associative.
778
     *
779
     * @param array $array the array being checked
780
     * @param bool $allStrings whether the array keys must be all strings in order for
781
     * the array to be treated as associative.
782
     * @return bool whether the array is associative
783
     */
784 12
    public static function isAssociative($array, $allStrings = true)
785
    {
786 12
        if (empty($array) || !is_array($array)) {
787 9
            return false;
788
        }
789
790 6
        if ($allStrings) {
791 6
            foreach ($array as $key => $value) {
792 6
                if (!is_string($key)) {
793 4
                    return false;
794
                }
795
            }
796
797 4
            return true;
798
        }
799
800 1
        foreach ($array as $key => $value) {
801 1
            if (is_string($key)) {
802 1
                return true;
803
            }
804
        }
805
806 1
        return false;
807
    }
808
809
    /**
810
     * Returns a value indicating whether the given array is an indexed array.
811
     *
812
     * An array is indexed if all its keys are integers. If `$consecutive` is true,
813
     * then the array keys must be a consecutive sequence starting from 0.
814
     *
815
     * Note that an empty array will be considered indexed.
816
     *
817
     * @param array $array the array being checked
818
     * @param bool $consecutive whether the array keys must be a consecutive sequence
819
     * in order for the array to be treated as indexed.
820
     * @return bool whether the array is indexed
821
     */
822 14
    public static function isIndexed($array, $consecutive = false)
823
    {
824 14
        if (!is_array($array)) {
0 ignored issues
show
introduced by
The condition is_array($array) is always true.
Loading history...
825 1
            return false;
826
        }
827
828 14
        if (empty($array)) {
829 1
            return true;
830
        }
831
832 14
        $keys = array_keys($array);
833
834 14
        if ($consecutive) {
835 1
            return $keys === array_keys($keys);
836
        }
837
838 14
        foreach ($keys as $key) {
839 14
            if (!is_int($key)) {
840 7
                return false;
841
            }
842
        }
843
844 8
        return true;
845
    }
846
847
    /**
848
     * Check whether an array or [[Traversable]] contains an element.
849
     *
850
     * This method does the same as the PHP function [in_array()](https://www.php.net/manual/en/function.in-array.php)
851
     * but additionally works for objects that implement the [[Traversable]] interface.
852
     *
853
     * @param mixed $needle The value to look for.
854
     * @param iterable $haystack The set of values to search.
855
     * @param bool $strict Whether to enable strict (`===`) comparison.
856
     * @return bool `true` if `$needle` was found in `$haystack`, `false` otherwise.
857
     * @throws InvalidArgumentException if `$haystack` is neither traversable nor an array.
858
     * @see https://www.php.net/manual/en/function.in-array.php
859
     * @since 2.0.7
860
     */
861 20
    public static function isIn($needle, $haystack, $strict = false)
862
    {
863 20
        if (!static::isTraversable($haystack)) {
864 1
            throw new InvalidArgumentException('Argument $haystack must be an array or implement Traversable');
865
        }
866
867 19
        if (is_array($haystack)) {
868 19
            return in_array($needle, $haystack, $strict);
869
        }
870
871 4
        foreach ($haystack as $value) {
872 4
            if ($strict ? $needle === $value : $needle == $value) {
873 4
                return true;
874
            }
875
        }
876
877 3
        return false;
878
    }
879
880
    /**
881
     * Checks whether a variable is an array or [[Traversable]].
882
     *
883
     * This method does the same as the PHP function [is_array()](https://www.php.net/manual/en/function.is-array.php)
884
     * but additionally works on objects that implement the [[Traversable]] interface.
885
     * @param mixed $var The variable being evaluated.
886
     * @return bool whether $var can be traversed via foreach
887
     * @see https://www.php.net/manual/en/function.is-array.php
888
     * @since 2.0.8
889
     */
890 90
    public static function isTraversable($var)
891
    {
892 90
        return is_array($var) || $var instanceof Traversable;
893
    }
894
895
    /**
896
     * Checks whether an array or [[Traversable]] is a subset of another array or [[Traversable]].
897
     *
898
     * This method will return `true`, if all elements of `$needles` are contained in
899
     * `$haystack`. If at least one element is missing, `false` will be returned.
900
     *
901
     * @param iterable $needles The values that must **all** be in `$haystack`.
902
     * @param iterable $haystack The set of value to search.
903
     * @param bool $strict Whether to enable strict (`===`) comparison.
904
     * @return bool `true` if `$needles` is a subset of `$haystack`, `false` otherwise.
905
     * @throws InvalidArgumentException if `$haystack` or `$needles` is neither traversable nor an array.
906
     * @since 2.0.7
907
     */
908 6
    public static function isSubset($needles, $haystack, $strict = false)
909
    {
910 6
        if (!static::isTraversable($needles)) {
911 1
            throw new InvalidArgumentException('Argument $needles must be an array or implement Traversable');
912
        }
913
914 5
        foreach ($needles as $needle) {
915 4
            if (!static::isIn($needle, $haystack, $strict)) {
916 3
                return false;
917
            }
918
        }
919
920 4
        return true;
921
    }
922
923
    /**
924
     * Filters array according to rules specified.
925
     *
926
     * For example:
927
     *
928
     * ```php
929
     * $array = [
930
     *     'A' => [1, 2],
931
     *     'B' => [
932
     *         'C' => 1,
933
     *         'D' => 2,
934
     *     ],
935
     *     'E' => 1,
936
     * ];
937
     *
938
     * $result = \yii\helpers\ArrayHelper::filter($array, ['A']);
939
     * // $result will be:
940
     * // [
941
     * //     'A' => [1, 2],
942
     * // ]
943
     *
944
     * $result = \yii\helpers\ArrayHelper::filter($array, ['A', 'B.C']);
945
     * // $result will be:
946
     * // [
947
     * //     'A' => [1, 2],
948
     * //     'B' => ['C' => 1],
949
     * // ]
950
     *
951
     * $result = \yii\helpers\ArrayHelper::filter($array, ['B', '!B.C']);
952
     * // $result will be:
953
     * // [
954
     * //     'B' => ['D' => 2],
955
     * // ]
956
     * ```
957
     *
958
     * @param array $array Source array
959
     * @param iterable $filters Rules that define array keys which should be left or removed from results.
960
     * Each rule is:
961
     * - `var` - `$array['var']` will be left in result.
962
     * - `var.key` = only `$array['var']['key'] will be left in result.
963
     * - `!var.key` = `$array['var']['key'] will be removed from result.
964
     * @return array Filtered array
965
     * @since 2.0.9
966
     */
967 26
    public static function filter($array, $filters)
968
    {
969 26
        $result = [];
970 26
        $excludeFilters = [];
971
972 26
        foreach ($filters as $filter) {
973 6
            if (!is_string($filter) && !is_int($filter)) {
974 1
                continue;
975
            }
976
977 5
            if (is_string($filter) && strncmp($filter, '!', 1) === 0) {
978 3
                $excludeFilters[] = substr($filter, 1);
979 3
                continue;
980
            }
981
982 5
            $nodeValue = $array; //set $array as root node
983 5
            $keys = explode('.', (string) $filter);
984 5
            foreach ($keys as $key) {
985 5
                if (!array_key_exists($key, $nodeValue)) {
986 2
                    continue 2; //Jump to next filter
987
                }
988 5
                $nodeValue = $nodeValue[$key];
989
            }
990
991
            //We've found a value now let's insert it
992 5
            $resultNode = &$result;
993 5
            foreach ($keys as $key) {
994 5
                if (!array_key_exists($key, $resultNode)) {
995 5
                    $resultNode[$key] = [];
996
                }
997 5
                $resultNode = &$resultNode[$key];
998
            }
999 5
            $resultNode = $nodeValue;
1000
        }
1001
1002 26
        foreach ($excludeFilters as $filter) {
1003 3
            $excludeNode = &$result;
1004 3
            $keys = explode('.', (string) $filter);
1005 3
            $numNestedKeys = count($keys) - 1;
1006 3
            foreach ($keys as $i => $key) {
1007 3
                if (!array_key_exists($key, $excludeNode)) {
1008 1
                    continue 2; //Jump to next filter
1009
                }
1010
1011 3
                if ($i < $numNestedKeys) {
1012 3
                    $excludeNode = &$excludeNode[$key];
1013
                } else {
1014 3
                    unset($excludeNode[$key]);
1015 3
                    break;
1016
                }
1017
            }
1018
        }
1019
1020 26
        return $result;
1021
    }
1022
1023
    /**
1024
     * Sorts array recursively.
1025
     *
1026
     * @param array $array An array passing by reference.
1027
     * @param callable|null $sorter The array sorter. If omitted, sort index array by values, sort assoc array by keys.
1028
     * @return array
1029
     */
1030 5
    public static function recursiveSort(array &$array, $sorter = null)
1031
    {
1032 5
        foreach ($array as &$value) {
1033 5
            if (is_array($value)) {
1034 2
                static::recursiveSort($value, $sorter);
1035
            }
1036
        }
1037 5
        unset($value);
1038
1039 5
        if ($sorter === null) {
1040 5
            $sorter = static::isIndexed($array) ? 'sort' : 'ksort';
1041
        }
1042
1043 5
        call_user_func_array($sorter, [&$array]);
1044
1045 5
        return $array;
1046
    }
1047
1048
    /**
1049
     * Flattens a multidimensional array into a one-dimensional array.
1050
     *
1051
     * This method recursively traverses the input array and concatenates the keys
1052
     * in a dot format to form a new key in the resulting array.
1053
     *
1054
     * Example:
1055
     *
1056
     * ```php
1057
     * $array = [
1058
     *      'A' => [1, 2],
1059
     *      'B' => [
1060
     *          'C' => 1,
1061
     *          'D' => 2,
1062
     *      ],
1063
     *      'E' => 1,
1064
     *  ];
1065
     * $result = \yii\helpers\ArrayHelper::flatten($array);
1066
     * // $result will be:
1067
     * // [
1068
     * //     'A.0' => 1
1069
     * //     'A.1' => 2
1070
     * //     'B.C' => 1
1071
     * //     'B.D' => 2
1072
     * //     'E' => 1
1073
     * // ]
1074
     * ```
1075
     *
1076
     * @param array $array the input array to be flattened in terms of name-value pairs.
1077
     * @param string $separator the separator to use between keys. Defaults to '.'.
1078
     *
1079
     * @return array the flattened array.
1080
     * @throws InvalidArgumentException if `$array` is neither traversable nor an array.
1081
     */
1082 25
    public static function flatten($array, $separator = '.'): array
1083
    {
1084 25
        if (!static::isTraversable($array)) {
1085 1
            throw new InvalidArgumentException('Argument $array must be an array or implement Traversable');
1086
        }
1087
1088 25
        $result = [];
1089
1090 25
        foreach ($array as $key => $value) {
1091 4
            $newKey = $key;
1092 4
            if (is_array($value)) {
1093 4
                $flattenedArray = self::flatten($value, $separator);
1094 4
                foreach ($flattenedArray as $subKey => $subValue) {
1095 4
                    $result[$newKey . $separator . $subKey] = $subValue;
1096
                }
1097
            } else {
1098 4
                $result[$newKey] = $value;
1099
            }
1100
        }
1101
1102 25
        return $result;
1103
    }
1104
}
1105