Passed
Pull Request — master (#56)
by Sergei
13:20
created

ArrayHelper::isTraversable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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
     * Below are some usage examples,
187
     *
188
     * ```php
189
     * // working with array
190
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($_POST, 'username');
191
     * // working with object
192
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($user, 'username');
193
     * // working with anonymous function
194
     * $fullName = \Yiisoft\Arrays\ArrayHelper::getValue($user, function ($user, $defaultValue) {
195
     *     return $user->firstName . ' ' . $user->lastName;
196
     * });
197
     * // using dot format to retrieve the property of embedded object
198
     * $street = \Yiisoft\Arrays\ArrayHelper::getValue($users, 'address.street');
199
     * // using an array of keys to retrieve the value
200
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
201
     * ```
202
     *
203
     * @param array|object $array array or object to extract value from
204
     * @param string|int|float|\Closure|array $key key name of the array element,
205
     * an array of keys or property name of the object, or an anonymous function
206
     * returning the value. The anonymous function signature should be:
207
     * `function($array, $defaultValue)`.
208
     * @param mixed $default the default value to be returned if the specified array key does not exist. Not used when
209
     * getting value from an object.
210
     * @return mixed the value of the element if found, default value otherwise
211
     */
212 61
    public static function getValue($array, $key, $default = null)
213
    {
214 61
        if ($key instanceof \Closure) {
215 8
            return $key($array, $default);
216
        }
217
218 58
        if (!is_array($array) && !is_object($array)) {
219 1
            throw new \InvalidArgumentException(
220 1
                'getValue() can not get value from ' . gettype($array) . '. Only array and object are supported.'
221
            );
222
        }
223
224 57
        if (is_array($key)) {
225 36
            $lastKey = array_pop($key);
226 36
            foreach ($key as $keyPart) {
227 33
                $array = static::getRootValue($array, $keyPart, $default);
228
            }
229 36
            return static::getRootValue($array, $lastKey, $default);
230
        }
231
232 23
        return static::getRootValue($array, $key, $default);
233
    }
234
235
    /**
236
     * @param array|object $array array or object to extract value from
237
     * @param string|int|float $key key name of the array element or property name of the object,
238
     * @param mixed $default the default value to be returned if the specified array key does not exist. Not used when
239
     * getting value from an object.
240
     * @return mixed the value of the element if found, default value otherwise
241
     */
242 57
    private static function getRootValue($array, $key, $default)
243
    {
244 57
        if (is_array($array) && array_key_exists((string)$key, $array)) {
245 39
            return $array[$key];
246
        }
247
248 32
        if (is_object($array)) {
249
            try {
250 14
                return $array::$$key;
251 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...
252
                // this is expected to fail if the property does not exist, or __get() is not implemented
253
                // it is not reliably possible to check whether a property is accessible beforehand
254 14
                return $array->$key;
255
            }
256
        }
257
258 18
        return $default;
259
    }
260
261
    /**
262
     * Retrieves the value of an array element or object property with the given key or property name.
263
     * If the key does not exist in the array or object, the default value will be returned instead.
264
     *
265
     * The key may be specified in a dot format to retrieve the value of a sub-array or the property
266
     * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
267
     * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
268
     * or `$array->x` is neither an array nor an object, the default value will be returned.
269
     * Note that if the array already has an element `x.y.z`, then its value will be returned
270
     * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
271
     * like `['x', 'y', 'z']`.
272
     *
273
     * Below are some usage examples,
274
     *
275
     * ```php
276
     * // working with array
277
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($_POST, 'username');
278
     * // working with object
279
     * $username = \Yiisoft\Arrays\ArrayHelper::getValue($user, 'username');
280
     * // working with anonymous function
281
     * $fullName = \Yiisoft\Arrays\ArrayHelper::getValue($user, function ($user, $defaultValue) {
282
     *     return $user->firstName . ' ' . $user->lastName;
283
     * });
284
     * // using dot format to retrieve the property of embedded object
285
     * $street = \Yiisoft\Arrays\ArrayHelper::getValue($users, 'address.street');
286
     * // using an array of keys to retrieve the value
287
     * $value = \Yiisoft\Arrays\ArrayHelper::getValue($versions, ['1.0', 'date']);
288
     * ```
289
     *
290
     * @param array|object $array array or object to extract value from
291
     * @param string|int|float|\Closure|array $path key name of the array element, an array of keys or property name
292
     * of the object, or an anonymous function returning the value. The anonymous function signature should be:
293
     * `function($array, $defaultValue)`.
294
     * @param mixed $default the default value to be returned if the specified array key does not exist. Not used when
295
     * getting value from an object.
296
     * @param string $delimiter
297
     * @return mixed the value of the element if found, default value otherwise
298
     */
299 31
    public static function getValueByPath($array, $path, $default = null, string $delimiter = '.')
300
    {
301 31
        return static::getValue($array, static::parsePath($path, $delimiter), $default);
302
    }
303
304
    /**
305
     * Writes a value into an associative array at the key path specified.
306
     * If there is no such key path yet, it will be created recursively.
307
     * If the key exists, it will be overwritten.
308
     *
309
     * ```php
310
     *  $array = [
311
     *      'key' => [
312
     *          'in' => [
313
     *              'val1',
314
     *              'key' => 'val'
315
     *          ]
316
     *      ]
317
     *  ];
318
     * ```
319
     *
320
     * The result of `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|int|float|array|null $key the path of where do you want to write a value to `$array`
335
     * the path can be described by an array of keys
336
     * if the path is null then `$array` will be assigned the `$value`
337
     * @param mixed $value the value to be written
338
     */
339 27
    public static function setValue(array &$array, $key, $value): void
340
    {
341 27
        if ($key === null) {
342 2
            $array = $value;
343 2
            return;
344
        }
345
346 25
        $keys = is_array($key) ? $key : [$key];
347
348 25
        while (count($keys) > 1) {
349 15
            $k = array_shift($keys);
350 15
            if (!isset($array[$k])) {
351 8
                $array[$k] = [];
352
            }
353 15
            if (!is_array($array[$k])) {
354 2
                $array[$k] = [$array[$k]];
355
            }
356 15
            $array = &$array[$k];
357
        }
358
359 25
        $array[array_shift($keys)] = $value;
360 25
    }
361
362
    /**
363
     * Writes a value into an associative array at the key path specified.
364
     * If there is no such key path yet, it will be created recursively.
365
     * If the key exists, it will be overwritten.
366
     *
367
     * ```php
368
     *  $array = [
369
     *      'key' => [
370
     *          'in' => [
371
     *              'val1',
372
     *              'key' => 'val'
373
     *          ]
374
     *      ]
375
     *  ];
376
     * ```
377
     *
378
     * The result of `ArrayHelper::setValue($array, 'key.in.0', ['arr' => 'val']);` will be the following:
379
     *
380
     * ```php
381
     *  [
382
     *      'key' => [
383
     *          'in' => [
384
     *              ['arr' => 'val'],
385
     *              'key' => 'val'
386
     *          ]
387
     *      ]
388
     *  ]
389
     *
390
     * ```
391
     *
392
     * The result of
393
     * `ArrayHelper::setValue($array, 'key.in', ['arr' => 'val']);` or
394
     * `ArrayHelper::setValue($array, ['key', 'in'], ['arr' => 'val']);`
395
     * will be the following:
396
     *
397
     * ```php
398
     *  [
399
     *      'key' => [
400
     *          'in' => [
401
     *              'arr' => 'val'
402
     *          ]
403
     *      ]
404
     *  ]
405
     * ```
406
     *
407
     * @param array $array the array to write the value to
408
     * @param string|int|float|array|null $path the path of where do you want to write a value to `$array`
409
     * the path can be described by a string when each key should be separated by a dot
410
     * you can also describe the path as an array of keys
411
     * if the path is null then `$array` will be assigned the `$value`
412
     * @param mixed $value the value to be written
413
     * @param string $delimiter
414
     */
415 20
    public static function setValueByPath(array &$array, $path, $value, string $delimiter = '.'): void
416
    {
417 20
        static::setValue($array, static::parsePath($path, $delimiter), $value);
418 20
    }
419
420
    /**
421
     * @param mixed $path
422
     * @param string $delimiter
423
     * @return mixed
424
     */
425 55
    private static function parsePath($path, string $delimiter)
426
    {
427 55
        if (is_string($path)) {
428 51
            return explode($delimiter, $path);
429
        }
430 16
        if (is_array($path)) {
431 12
            $newPath = [];
432 12
            foreach ($path as $key) {
433 12
                if (is_string($key) || is_array($key)) {
434 12
                    $newPath = array_merge($newPath, static::parsePath($key, $delimiter));
435
                } else {
436 2
                    $newPath[] = $key;
437
                }
438
            }
439 12
            return $newPath;
440
        }
441 4
        return $path;
442
    }
443
444
    /**
445
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
446
     * will be returned instead.
447
     *
448
     * Usage examples,
449
     *
450
     * ```php
451
     * // $array = ['type' => 'A', 'options' => [1, 2]];
452
     * // working with array
453
     * $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
454
     * // $array content
455
     * // $array = ['options' => [1, 2]];
456
     * ```
457
     *
458
     * @param array $array the array to extract value from
459
     * @param string|int|float|array $key key name of the array element or associative array at the key path specified
460
     * @param mixed $default the default value to be returned if the specified key does not exist
461
     * @return mixed the value of the element if found, default value otherwise
462
     */
463 12
    public static function remove(array &$array, $key, $default = null)
464
    {
465 12
        $keys = is_array($key) ? $key : [$key];
466
467 12
        while (count($keys) > 1) {
468 7
            $key = array_shift($keys);
469 7
            if (!isset($array[$key]) || !is_array($array[$key])) {
470 1
                return $default;
471
            }
472 6
            $array = &$array[$key];
473
        }
474
475 11
        $key = array_shift($keys);
476 11
        if (array_key_exists((string)$key, $array)) {
477 10
            $value = $array[$key];
478 10
            unset($array[$key]);
479 10
            return $value;
480
        }
481
482 1
        return $default;
483
    }
484
485
    /**
486
     * Removes an item from an array and returns the value. If the key does not exist in the array, the default value
487
     * will be returned instead.
488
     *
489
     * Usage examples,
490
     *
491
     * ```php
492
     * // $array = ['type' => 'A', 'options' => [1, 2]];
493
     * // working with array
494
     * $type = \Yiisoft\Arrays\ArrayHelper::remove($array, 'type');
495
     * // $array content
496
     * // $array = ['options' => [1, 2]];
497
     * ```
498
     *
499
     * @param array $array the array to extract value from
500
     * @param string|array $path key name of the array element or associative array at the key path specified
501
     * the path can be described by a string when each key should be separated by a delimiter (default is dot)
502
     * @param mixed $default the default value to be returned if the specified key does not exist
503
     * @param string $delimiter
504
     * @return mixed the value of the element if found, default value otherwise
505
     */
506 5
    public static function removeByPath(array &$array, $path, $default = null, string $delimiter = '.')
507
    {
508 5
        return static::remove($array, static::parsePath($path, $delimiter), $default);
509
    }
510
511
    /**
512
     * Removes items with matching values from the array and returns the removed items.
513
     *
514
     * Example,
515
     *
516
     * ```php
517
     * $array = ['Bob' => 'Dylan', 'Michael' => 'Jackson', 'Mick' => 'Jagger', 'Janet' => 'Jackson'];
518
     * $removed = \Yiisoft\Arrays\ArrayHelper::removeValue($array, 'Jackson');
519
     * // result:
520
     * // $array = ['Bob' => 'Dylan', 'Mick' => 'Jagger'];
521
     * // $removed = ['Michael' => 'Jackson', 'Janet' => 'Jackson'];
522
     * ```
523
     *
524
     * @param array $array the array where to look the value from
525
     * @param mixed $value the value to remove from the array
526
     * @return array the items that were removed from the array
527
     */
528 2
    public static function removeValue(array &$array, $value): array
529
    {
530 2
        $result = [];
531 2
        foreach ($array as $key => $val) {
532 2
            if ($val === $value) {
533 1
                $result[$key] = $val;
534 1
                unset($array[$key]);
535
            }
536
        }
537
538 2
        return $result;
539
    }
540
541
    /**
542
     * Indexes and/or groups the array according to a specified key.
543
     * The input should be either multidimensional array or an array of objects.
544
     *
545
     * The $key can be either a key name of the sub-array, a property name of object, or an anonymous
546
     * function that must return the value that will be used as a key.
547
     *
548
     * $groups is an array of keys, that will be used to group the input array into one or more sub-arrays based
549
     * on keys specified.
550
     *
551
     * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
552
     * to `$groups` not specified then the element is discarded.
553
     *
554
     * For example:
555
     *
556
     * ```php
557
     * $array = [
558
     *     ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
559
     *     ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
560
     *     ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
561
     * ];
562
     * $result = ArrayHelper::index($array, 'id');
563
     * ```
564
     *
565
     * The result will be an associative array, where the key is the value of `id` attribute
566
     *
567
     * ```php
568
     * [
569
     *     '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
570
     *     '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
571
     *     // The second element of an original array is overwritten by the last element because of the same id
572
     * ]
573
     * ```
574
     *
575
     * An anonymous function can be used in the grouping array as well.
576
     *
577
     * ```php
578
     * $result = ArrayHelper::index($array, function ($element) {
579
     *     return $element['id'];
580
     * });
581
     * ```
582
     *
583
     * Passing `id` as a third argument will group `$array` by `id`:
584
     *
585
     * ```php
586
     * $result = ArrayHelper::index($array, null, 'id');
587
     * ```
588
     *
589
     * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
590
     * and indexed by `data` on the third level:
591
     *
592
     * ```php
593
     * [
594
     *     '123' => [
595
     *         ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
596
     *     ],
597
     *     '345' => [ // all elements with this index are present in the result array
598
     *         ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
599
     *         ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
600
     *     ]
601
     * ]
602
     * ```
603
     *
604
     * The anonymous function can be used in the array of grouping keys as well:
605
     *
606
     * ```php
607
     * $result = ArrayHelper::index($array, 'data', [function ($element) {
608
     *     return $element['id'];
609
     * }, 'device']);
610
     * ```
611
     *
612
     * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
613
     * and indexed by the `data` on the third level:
614
     *
615
     * ```php
616
     * [
617
     *     '123' => [
618
     *         'laptop' => [
619
     *             'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
620
     *         ]
621
     *     ],
622
     *     '345' => [
623
     *         'tablet' => [
624
     *             'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
625
     *         ],
626
     *         'smartphone' => [
627
     *             'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
628
     *         ]
629
     *     ]
630
     * ]
631
     * ```
632
     *
633
     * @param array $array the array that needs to be indexed or grouped
634
     * @param string|\Closure|null $key the column name or anonymous function which result will be used to index the array
635
     * @param string|string[]|\Closure[]|null $groups the array of keys, that will be used to group the input array
636
     * by one or more keys. If the $key attribute or its value for the particular element is null and $groups is not
637
     * defined, the array element will be discarded. Otherwise, if $groups is specified, array element will be added
638
     * to the result array without any key.
639
     * @return array the indexed and/or grouped array
640
     */
641 3
    public static function index(array $array, $key, $groups = []): array
642
    {
643 3
        $result = [];
644 3
        $groups = (array)$groups;
645
646 3
        foreach ($array as $element) {
647 3
            $lastArray = &$result;
648
649 3
            foreach ($groups as $group) {
650 1
                $value = static::getValue($element, $group);
651 1
                if (!array_key_exists($value, $lastArray)) {
652 1
                    $lastArray[$value] = [];
653
                }
654 1
                $lastArray = &$lastArray[$value];
655
            }
656
657 3
            if ($key === null) {
658 2
                if (!empty($groups)) {
659 2
                    $lastArray[] = $element;
660
                }
661
            } else {
662 3
                $value = static::getValue($element, $key);
663 3
                if ($value !== null) {
664 3
                    if (is_float($value)) {
665 1
                        $value = str_replace(',', '.', (string)$value);
666
                    }
667 3
                    $lastArray[$value] = $element;
668
                }
669
            }
670 3
            unset($lastArray);
671
        }
672
673 3
        return $result;
674
    }
675
676
    /**
677
     * Returns the values of a specified column in an array.
678
     * The input array should be multidimensional or an array of objects.
679
     *
680
     * For example,
681
     *
682
     * ```php
683
     * $array = [
684
     *     ['id' => '123', 'data' => 'abc'],
685
     *     ['id' => '345', 'data' => 'def'],
686
     * ];
687
     * $result = ArrayHelper::getColumn($array, 'id');
688
     * // the result is: ['123', '345']
689
     *
690
     * // using anonymous function
691
     * $result = ArrayHelper::getColumn($array, function ($element) {
692
     *     return $element['id'];
693
     * });
694
     * ```
695
     *
696
     * @param array $array
697
     * @param string|\Closure $name
698
     * @param bool $keepKeys whether to maintain the array keys. If false, the resulting array
699
     * will be re-indexed with integers.
700
     * @return array the list of column values
701
     */
702 5
    public static function getColumn(array $array, $name, bool $keepKeys = true): array
703
    {
704 5
        $result = [];
705 5
        if ($keepKeys) {
706 5
            foreach ($array as $k => $element) {
707 5
                $result[$k] = static::getValue($element, $name);
708
            }
709
        } else {
710 1
            foreach ($array as $element) {
711 1
                $result[] = static::getValue($element, $name);
712
            }
713
        }
714
715 5
        return $result;
716
    }
717
718
    /**
719
     * Builds a map (key-value pairs) from a multidimensional array or an array of objects.
720
     * The `$from` and `$to` parameters specify the key names or property names to set up the map.
721
     * Optionally, one can further group the map according to a grouping field `$group`.
722
     *
723
     * For example,
724
     *
725
     * ```php
726
     * $array = [
727
     *     ['id' => '123', 'name' => 'aaa', 'class' => 'x'],
728
     *     ['id' => '124', 'name' => 'bbb', 'class' => 'x'],
729
     *     ['id' => '345', 'name' => 'ccc', 'class' => 'y'],
730
     * ];
731
     *
732
     * $result = ArrayHelper::map($array, 'id', 'name');
733
     * // the result is:
734
     * // [
735
     * //     '123' => 'aaa',
736
     * //     '124' => 'bbb',
737
     * //     '345' => 'ccc',
738
     * // ]
739
     *
740
     * $result = ArrayHelper::map($array, 'id', 'name', 'class');
741
     * // the result is:
742
     * // [
743
     * //     'x' => [
744
     * //         '123' => 'aaa',
745
     * //         '124' => 'bbb',
746
     * //     ],
747
     * //     'y' => [
748
     * //         '345' => 'ccc',
749
     * //     ],
750
     * // ]
751
     * ```
752
     *
753
     * @param array $array
754
     * @param string|\Closure $from
755
     * @param string|\Closure $to
756
     * @param string|\Closure $group
757
     * @return array
758
     */
759 1
    public static function map(array $array, $from, $to, $group = null): array
760
    {
761 1
        if ($group === null) {
762 1
            return array_column($array, $to, $from);
763
        }
764
765 1
        $result = [];
766 1
        foreach ($array as $element) {
767 1
            $key = static::getValue($element, $from);
768 1
            $result[static::getValue($element, $group)][$key] = static::getValue($element, $to);
769
        }
770
771 1
        return $result;
772
    }
773
774
    /**
775
     * Checks if the given array contains the specified key.
776
     * This method enhances the `array_key_exists()` function by supporting case-insensitive
777
     * key comparison.
778
     * @param array $array the array with keys to check
779
     * @param string $key the key to check
780
     * @param bool $caseSensitive whether the key comparison should be case-sensitive
781
     * @return bool whether the array contains the specified key
782
     */
783 1
    public static function keyExists(array $array, string $key, bool $caseSensitive = true): bool
784
    {
785 1
        if ($caseSensitive) {
786 1
            return array_key_exists($key, $array);
787
        }
788
789 1
        foreach (array_keys($array) as $k) {
790 1
            if (strcasecmp($key, $k) === 0) {
791 1
                return true;
792
            }
793
        }
794
795 1
        return false;
796
    }
797
798
    /**
799
     * Encodes special characters in an array of strings into HTML entities.
800
     * Only array values will be encoded by default.
801
     * If a value is an array, this method will also encode it recursively.
802
     * Only string values will be encoded.
803
     * @param array $data data to be encoded
804
     * @param bool $valuesOnly whether to encode array values only. If false,
805
     * both the array keys and array values will be encoded.
806
     * @param string|null $encoding The encoding to use, defaults to `ini_get('default_charset')`.
807
     * @return array the encoded data
808
     * @see http://www.php.net/manual/en/function.htmlspecialchars.php
809
     */
810 1
    public static function htmlEncode(array $data, bool $valuesOnly = true, string $encoding = null): array
811
    {
812 1
        $d = [];
813 1
        foreach ($data as $key => $value) {
814 1
            if (!$valuesOnly && is_string($key)) {
815 1
                $key = htmlspecialchars($key, ENT_QUOTES | ENT_SUBSTITUTE, $encoding, true);
816
            }
817 1
            if (is_string($value)) {
818 1
                $d[$key] = htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, $encoding, true);
819 1
            } elseif (is_array($value)) {
820 1
                $d[$key] = static::htmlEncode($value, $valuesOnly, $encoding);
821
            } else {
822 1
                $d[$key] = $value;
823
            }
824
        }
825
826 1
        return $d;
827
    }
828
829
    /**
830
     * Decodes HTML entities into the corresponding characters in an array of strings.
831
     * Only array values will be decoded by default.
832
     * If a value is an array, this method will also decode it recursively.
833
     * Only string values will be decoded.
834
     * @param array $data data to be decoded
835
     * @param bool $valuesOnly whether to decode array values only. If false,
836
     * both the array keys and array values will be decoded.
837
     * @return array the decoded data
838
     * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php
839
     */
840 1
    public static function htmlDecode(array $data, bool $valuesOnly = true): array
841
    {
842 1
        $d = [];
843 1
        foreach ($data as $key => $value) {
844 1
            if (!$valuesOnly && is_string($key)) {
845 1
                $key = htmlspecialchars_decode($key, ENT_QUOTES);
846
            }
847 1
            if (is_string($value)) {
848 1
                $d[$key] = htmlspecialchars_decode($value, ENT_QUOTES);
849 1
            } elseif (is_array($value)) {
850 1
                $d[$key] = static::htmlDecode($value);
851
            } else {
852 1
                $d[$key] = $value;
853
            }
854
        }
855
856 1
        return $d;
857
    }
858
859
    /**
860
     * Returns a value indicating whether the given array is an associative array.
861
     *
862
     * An array is associative if all its keys are strings. If `$allStrings` is false,
863
     * then an array will be treated as associative if at least one of its keys is a string.
864
     *
865
     * Note that an empty array will NOT be considered associative.
866
     *
867
     * @param array $array the array being checked
868
     * @param bool $allStrings whether the array keys must be all strings in order for
869
     * the array to be treated as associative.
870
     * @return bool whether the array is associative
871
     */
872 1
    public static function isAssociative(array $array, bool $allStrings = true): bool
873
    {
874 1
        if ($array === []) {
875 1
            return false;
876
        }
877
878 1
        if ($allStrings) {
879 1
            foreach ($array as $key => $value) {
880 1
                if (!is_string($key)) {
881 1
                    return false;
882
                }
883
            }
884
885 1
            return true;
886
        }
887
888 1
        foreach ($array as $key => $value) {
889 1
            if (is_string($key)) {
890 1
                return true;
891
            }
892
        }
893
894 1
        return false;
895
    }
896
897
    /**
898
     * Returns a value indicating whether the given array is an indexed array.
899
     *
900
     * An array is indexed if all its keys are integers. If `$consecutive` is true,
901
     * then the array keys must be a consecutive sequence starting from 0.
902
     *
903
     * Note that an empty array will be considered indexed.
904
     *
905
     * @param array $array the array being checked
906
     * @param bool $consecutive whether the array keys must be a consecutive sequence
907
     * in order for the array to be treated as indexed.
908
     * @return bool whether the array is indexed
909
     */
910 1
    public static function isIndexed(array $array, bool $consecutive = false): bool
911
    {
912 1
        if ($array === []) {
913 1
            return true;
914
        }
915
916 1
        if ($consecutive) {
917 1
            return array_keys($array) === range(0, count($array) - 1);
918
        }
919
920 1
        foreach ($array as $key => $value) {
921 1
            if (!is_int($key)) {
922 1
                return false;
923
            }
924
        }
925
926 1
        return true;
927
    }
928
929
    /**
930
     * Check whether an array or [[\Traversable]] contains an element.
931
     *
932
     * This method does the same as the PHP function [in_array()](http://php.net/manual/en/function.in-array.php)
933
     * but additionally works for objects that implement the [[\Traversable]] interface.
934
     * @param mixed $needle The value to look for.
935
     * @param iterable $haystack The set of values to search.
936
     * @param bool $strict Whether to enable strict (`===`) comparison.
937
     * @return bool `true` if `$needle` was found in `$haystack`, `false` otherwise.
938
     * @throws InvalidArgumentException if `$haystack` is neither traversable nor an array.
939
     * @see http://php.net/manual/en/function.in-array.php
940
     */
941 3
    public static function isIn($needle, iterable $haystack, bool $strict = false): bool
942
    {
943 3
        if (is_array($haystack)) {
944 3
            return in_array($needle, $haystack, $strict);
945
        }
946
947 3
        foreach ($haystack as $value) {
948 3
            if ($needle == $value && (!$strict || $needle === $value)) {
949 3
                return true;
950
            }
951
        }
952
953 3
        return false;
954
    }
955
956
    /**
957
     * Checks whether an array or [[\Traversable]] is a subset of another array or [[\Traversable]].
958
     *
959
     * This method will return `true`, if all elements of `$needles` are contained in
960
     * `$haystack`. If at least one element is missing, `false` will be returned.
961
     * @param iterable $needles The values that must **all** be in `$haystack`.
962
     * @param iterable $haystack The set of value to search.
963
     * @param bool $strict Whether to enable strict (`===`) comparison.
964
     * @return bool `true` if `$needles` is a subset of `$haystack`, `false` otherwise.
965 1
     * @throws InvalidArgumentException if `$haystack` or `$needles` is neither traversable nor an array.
966
     */
967 1
    public static function isSubset(iterable $needles, iterable $haystack, bool $strict = false): bool
968
    {
969
        foreach ($needles as $needle) {
970
            if (!static::isIn($needle, $haystack, $strict)) {
971
                return false;
972
            }
973
        }
974
975
        return true;
976
    }
977
978
    /**
979
     * Filters array according to rules specified.
980
     *
981 1
     * For example:
982
     *
983 1
     * ```php
984 1
     * $array = [
985 1
     *     'A' => [1, 2],
986
     *     'B' => [
987
     *         'C' => 1,
988
     *         'D' => 2,
989 1
     *     ],
990
     *     'E' => 1,
991
     * ];
992
     *
993
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['A']);
994
     * // $result will be:
995
     * // [
996
     * //     'A' => [1, 2],
997
     * // ]
998
     *
999
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['A', 'B.C']);
1000
     * // $result will be:
1001
     * // [
1002
     * //     'A' => [1, 2],
1003
     * //     'B' => ['C' => 1],
1004
     * // ]
1005
     *
1006
     * $result = \Yiisoft\Arrays\ArrayHelper::filter($array, ['B', '!B.C']);
1007
     * // $result will be:
1008
     * // [
1009
     * //     'B' => ['D' => 2],
1010
     * // ]
1011
     * ```
1012
     *
1013
     * @param array $array Source array
1014
     * @param array $filters Rules that define array keys which should be left or removed from results.
1015
     * Each rule is:
1016
     * - `var` - `$array['var']` will be left in result.
1017
     * - `var.key` = only `$array['var']['key'] will be left in result.
1018
     * - `!var.key` = `$array['var']['key'] will be removed from result.
1019
     * @return array Filtered array
1020
     */
1021
    public static function filter(array $array, array $filters): array
1022
    {
1023
        $result = [];
1024
        $excludeFilters = [];
1025
1026
        foreach ($filters as $filter) {
1027
            if ($filter[0] === '!') {
1028
                $excludeFilters[] = substr($filter, 1);
1029
                continue;
1030
            }
1031
1032
            $nodeValue = $array; //set $array as root node
1033
            $keys = explode('.', $filter);
1034
            foreach ($keys as $key) {
1035 3
                if (!array_key_exists($key, $nodeValue)) {
1036
                    continue 2; //Jump to next filter
1037 3
                }
1038 3
                $nodeValue = $nodeValue[$key];
1039
            }
1040 3
1041 3
            //We've found a value now let's insert it
1042 1
            $resultNode = &$result;
1043 1
            foreach ($keys as $key) {
1044
                if (!array_key_exists($key, $resultNode)) {
1045
                    $resultNode[$key] = [];
1046 3
                }
1047 3
                $resultNode = &$resultNode[$key];
1048 3
            }
1049 3
            $resultNode = $nodeValue;
1050 1
        }
1051
1052 3
        foreach ($excludeFilters as $filter) {
1053
            $excludeNode = &$result;
1054
            $keys = explode('.', $filter);
1055
            $numNestedKeys = count($keys) - 1;
1056 2
            foreach ($keys as $i => $key) {
1057 2
                if (!array_key_exists($key, $excludeNode)) {
1058 2
                    continue 2; //Jump to next filter
1059 2
                }
1060
1061 2
                if ($i < $numNestedKeys) {
1062
                    $excludeNode = &$excludeNode[$key];
1063 2
                } else {
1064
                    unset($excludeNode[$key]);
1065
                    break;
1066 3
                }
1067 1
            }
1068 1
        }
1069 1
1070 1
        return $result;
1071 1
    }
1072 1
1073
    /**
1074
     * Returns the public member variables of an object.
1075 1
     * This method is provided such that we can get the public member variables of an object.
1076 1
     * It is different from "get_object_vars()" because the latter will return private
1077
     * and protected variables if it is called within the object itself.
1078 1
     * @param object $object the object to be handled
1079 1
     * @return array|null the public member variables of the object or null if not object given
1080
     */
1081
    public static function getObjectVars(object $object): ?array
1082
    {
1083
        return get_object_vars($object);
1084 3
    }
1085
}
1086