Passed
Push — master ( 8046d3...0f004d )
by Paweł
19:40
created

BaseArrayHelper::recursiveSort()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

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