Passed
Pull Request — master (#19594)
by
unknown
09:00
created

BaseArrayHelper::isSubset()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

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