Passed
Pull Request — master (#51)
by
unknown
13:01
created

ArrayHelper::setValue()   B

Complexity

Conditions 10
Paths 12

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 10

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 26
ccs 14
cts 14
cp 1
rs 7.6666
cc 10
nc 12
nop 3
crap 10

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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