Passed
Pull Request — master (#20065)
by
unknown
12:48
created

BaseArrayHelper::toArray()   C

Complexity

Conditions 17
Paths 18

Size

Total Lines 45
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 17.0131

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 17
eloc 29
c 1
b 0
f 0
nc 18
nop 3
dl 0
loc 45
ccs 27
cts 28
cp 0.9643
crap 17.0131
rs 5.2166

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 35
    public static function toArray($object, $properties = [], $recursive = true)
62
    {
63 35
        if (is_array($object)) {
64 35
            if ($recursive) {
65 35
                foreach ($object as $key => $value) {
66 35
                    if ($value instanceof \UnitEnum) {
0 ignored issues
show
Bug introduced by
The type UnitEnum was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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