Completed
Push — arrayhelper-error ( e963b2 )
by Carsten
16:45
created

BaseArrayHelper::htmlDecode()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
ccs 14
cts 14
cp 1
cc 6
eloc 12
nc 7
nop 2
crap 6
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 Yii;
11
use yii\base\Arrayable;
12
use yii\base\InvalidParamException;
13
14
/**
15
 * BaseArrayHelper provides concrete implementation for [[ArrayHelper]].
16
 *
17
 * Do not use BaseArrayHelper. Use [[ArrayHelper]] instead.
18
 *
19
 * @author Qiang Xue <[email protected]>
20
 * @since 2.0
21
 */
22
class BaseArrayHelper
23
{
24
    /**
25
     * Converts an object or an array of objects into an array.
26
     * @param object|array|string $object the object to be converted into an array
27
     * @param array $properties a mapping from object class names to the properties that need to put into the resulting arrays.
28
     * The properties specified for each class is an array of the following format:
29
     *
30
     * ```php
31
     * [
32
     *     'app\models\Post' => [
33
     *         'id',
34
     *         'title',
35
     *         // the key name in array result => property name
36
     *         'createTime' => 'created_at',
37
     *         // the key name in array result => anonymous function
38
     *         'length' => function ($post) {
39
     *             return strlen($post->content);
40
     *         },
41
     *     ],
42
     * ]
43
     * ```
44
     *
45
     * The result of `ArrayHelper::toArray($post, $properties)` could be like the following:
46
     *
47
     * ```php
48
     * [
49
     *     'id' => 123,
50
     *     'title' => 'test',
51
     *     'createTime' => '2013-01-01 12:00AM',
52
     *     'length' => 301,
53
     * ]
54
     * ```
55
     *
56
     * @param bool $recursive whether to recursively converts properties which are objects into arrays.
57
     * @return array the array representation of the object
58
     */
59 11
    public static function toArray($object, $properties = [], $recursive = true)
60
    {
61 11
        if (is_array($object)) {
62 11
            if ($recursive) {
63 11
                foreach ($object as $key => $value) {
64 11
                    if (is_array($value) || is_object($value)) {
65 1
                        $object[$key] = static::toArray($value, $properties, true);
66 1
                    }
67 11
                }
68 11
            }
69
70 11
            return $object;
71 1
        } elseif (is_object($object)) {
72 1
            if (!empty($properties)) {
73 1
                $className = get_class($object);
74 1
                if (!empty($properties[$className])) {
75 1
                    $result = [];
76 1
                    foreach ($properties[$className] as $key => $name) {
77 1
                        if (is_int($key)) {
78 1
                            $result[$name] = $object->$name;
79 1
                        } else {
80 1
                            $result[$key] = static::getValue($object, $name);
81
                        }
82 1
                    }
83
84 1
                    return $recursive ? static::toArray($result, $properties) : $result;
85
                }
86 1
            }
87 1
            if ($object instanceof Arrayable) {
88
                $result = $object->toArray([], [], $recursive);
89
            } else {
90 1
                $result = [];
91 1
                foreach ($object as $key => $value) {
92 1
                    $result[$key] = $value;
93 1
                }
94
            }
95
96 1
            return $recursive ? static::toArray($result, $properties) : $result;
97
        } else {
98
            return [$object];
99
        }
100
    }
101
102
    /**
103
     * Merges two or more arrays into one recursively.
104
     * If each array has an element with the same string key value, the latter
105
     * will overwrite the former (different from array_merge_recursive).
106
     * Recursive merging will be conducted if both arrays have an element of array
107
     * type and are having the same key.
108
     * For integer-keyed elements, the elements from the latter array will
109
     * be appended to the former array.
110
     * You can use [[UnsetArrayValue]] object to unset value from previous array or
111
     * [[ReplaceArrayValue]] to force replace former value instead of recursive merging.
112
     * @param array $a array to be merged to
113
     * @param array $b array to be merged from. You can specify additional
114
     * arrays via third argument, fourth argument etc.
115
     * @return array the merged array (the original arrays are not changed.)
116
     */
117 2299
    public static function merge($a, $b)
0 ignored issues
show
Unused Code introduced by
The parameter $a is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $b is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

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