Completed
Push — master ( 2f9f15...59002a )
by Alexander
43:26 queued 40:20
created

BaseArrayHelper::setValue()   B

Complexity

Conditions 6
Paths 11

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

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