Passed
Pull Request — master (#62)
by Sergei
06:40 queued 04:40
created

ArrayHelper::performMerge()   B

Complexity

Conditions 10
Paths 6

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 10

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
dl 0
loc 20
ccs 12
cts 12
cp 1
rs 7.6666
c 1
b 0
f 0
cc 10
nc 6
nop 1
crap 10

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

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