Passed
Pull Request — master (#46)
by Sergei
13:42
created

ArrayHelper::getRootValue()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

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