Passed
Pull Request — master (#50)
by Sergei
11:32
created

ArrayHelper::getValueByPath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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