Passed
Push — 2.2 ( c9917f...37714b )
by Alexander
02:01 queued 17s
created

BaseArrayHelper::getValue()   C

Complexity

Conditions 13
Paths 17

Size

Total Lines 44
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 13

Importance

Changes 0
Metric Value
cc 13
eloc 24
nc 17
nop 3
dl 0
loc 44
ccs 24
cts 24
cp 1
crap 13
rs 6.6166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

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