Passed
Pull Request — master (#52)
by Sergei
01:28
created

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