BaseArrayHelper::htmlEncode()   B
last analyzed

Complexity

Conditions 8
Paths 21

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 8

Importance

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