Passed
Push — 18086-fix-arrayhelper ( 46281e...31395a )
by Alexander
80:44 queued 77:34
created

BaseArrayHelper   F

Complexity

Total Complexity 135

Size/Duplication

Total Lines 967
Duplicated Lines 0 %

Test Coverage

Coverage 99.23%

Importance

Changes 5
Bugs 1 Features 0
Metric Value
eloc 252
c 5
b 1
f 0
dl 0
loc 967
ccs 258
cts 260
cp 0.9923
rs 2
wmc 135

19 Methods

Rating   Name   Duplication   Size   Complexity  
C toArray() 0 41 15
B merge() 0 25 10
B index() 0 33 8
A isTraversable() 0 3 2
B keyExists() 0 23 9
B multisort() 0 33 9
A htmlDecode() 0 17 6
A map() 0 14 3
A setValue() 0 21 6
A remove() 0 10 4
A getColumn() 0 14 4
B isAssociative() 0 23 8
A removeValue() 0 13 4
B isIn() 0 15 7
A isIndexed() 0 21 6
B htmlEncode() 0 20 8
B getValue() 0 40 10
B filter() 0 50 11
A isSubset() 0 13 5

How to fix   Complexity   

Complex Class

Complex classes like BaseArrayHelper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BaseArrayHelper, and based on these observations, apply Extract Interface, too.

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