Passed
Push — main ( 56b58d...428ea0 )
by Andrey
14:59 queued 13:09
created

Arr::flatten()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 6
eloc 11
nc 10
nop 2
dl 0
loc 21
ccs 12
cts 12
cp 1
crap 6
rs 9.2222
c 2
b 1
f 0
1
<?php
2
/*
3
 * This file is part of the "andrey-helldar/support" project.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @author Andrey Helldar <[email protected]>
9
 *
10
 * @copyright 2021 Andrey Helldar
11
 *
12
 * @license MIT
13
 *
14
 * @see https://github.com/andrey-helldar/support
15
 */
16
17
namespace Helldar\Support\Helpers;
18
19
use ArrayAccess;
20
use ArrayObject;
21
use Helldar\Contracts\Support\Arrayable;
22
use Helldar\Support\Facades\Callbacks\Empties;
23
use Helldar\Support\Facades\Callbacks\Sorter;
24
use Helldar\Support\Facades\Helpers\Call as CallHelper;
25
use Helldar\Support\Facades\Helpers\Filesystem\File;
26
use Helldar\Support\Facades\Helpers\Instance as InstanceHelper;
27
use Helldar\Support\Facades\Tools\Stub;
28
use Helldar\Support\Helpers\Ables\Arrayable as ArrayableHelper;
29
use Helldar\Support\Tools\Stub as StubTool;
30
31
class Arr
32
{
33
    /**
34
     * Get a new arrayable object from the given array.
35
     *
36
     * @param  array|ArrayAccess|string|null  $value
37
     *
38
     * @return \Helldar\Support\Helpers\Ables\Arrayable
39
     */
40 1
    public function of($value = []): Ables\Arrayable
41
    {
42 1
        return new Ables\Arrayable($value);
43
    }
44
45
    /**
46
     * Renaming array keys.
47
     * As the second parameter, a callback function is passed, which determines the actions for processing the value.
48
     * The output of the function must be a string with a name.
49
     *
50
     * @param  array  $array
51
     * @param  callable  $callback
52
     *
53
     * @return array
54
     */
55 10
    public function renameKeys(array $array, callable $callback): array
56
    {
57 10
        $result = [];
58
59 10
        foreach ($array as $key => $value) {
60 10
            $new = $callback($key, $value);
61
62 10
            $result[$new] = $value;
63
        }
64
65 10
        return $result;
66
    }
67
68
    /**
69
     * Renaming array keys with map.
70
     *
71
     * @param  array  $array
72
     * @param  array  $map
73
     *
74
     * @return array
75
     */
76 4
    public function renameKeysMap(array $array, array $map): array
77
    {
78 4
        return $this->renameKeys($array, static function ($key) use ($map) {
79 4
            return $map[$key] ?? $key;
80 4
        });
81
    }
82
83
    /**
84
     * Get the size of the longest text element of the array.
85
     *
86
     * @param  array  $array
87
     *
88
     * @return int
89
     */
90 2
    public function longestStringLength(array $array): int
91
    {
92 2
        return ! empty($array) ? max(array_map('mb_strlen', $array)) : 0;
93
    }
94
95
    /**
96
     * Push one a unique element onto the end of array.
97
     *
98
     * @param  array  $array
99
     * @param  mixed  $values
100
     *
101
     * @return array
102
     */
103 6
    public function addUnique(array $array, $values): array
104
    {
105 6
        if ($this->isArrayable($values)) {
106 6
            foreach ($values as $value) {
107 6
                $array = $this->addUnique($array, $value);
108
            }
109
        } else {
110 6
            array_push($array, $values);
111
        }
112
113 6
        return $this->unique($array);
114
    }
115
116
    /**
117
     * Removes duplicate values from an array.
118
     *
119
     * Sorting type flags:
120
     *   SORT_REGULAR       - compare items normally
121
     *   SORT_NUMERIC       - compare items numerically
122
     *   SORT_STRING        - compare items as strings
123
     *   SORT_LOCALE_STRING - compare items as strings, based on the current locale
124
     *
125
     * @see https://php.net/manual/en/function.array-unique.php
126
     *
127
     * @param  array  $array
128
     * @param  int  $flags
129
     *
130
     * @return array
131
     */
132 10
    public function unique(array $array, int $flags = SORT_STRING): array
133
    {
134 10
        return array_unique($array, $flags);
135
    }
136
137
    /**
138
     * Sort an associative array in the order specified by an array of keys.
139
     *
140
     * Example:
141
     *
142
     *  $arr = ['q' => 1, 'r' => 2, 's' => 5, 'w' => 123];
143
     *
144
     *  Arr::sortByKeys($arr, ['q', 'w', 'e']);
145
     *
146
     * print_r($arr);
147
     *
148
     *   Array
149
     *   (
150
     *     [q] => 1
151
     *     [w] => 123
152
     *     [r] => 2
153
     *     [s] => 5
154
     *   )
155
     *
156
     * @see https://gist.github.com/Ellrion/a3145621f936aa9416f4c04987533d8d#file-helper-php
157
     *
158
     * @param  array  $array
159
     * @param  array  $sorter
160
     *
161
     * @return array
162
     */
163 4
    public function sortByKeys(array $array, array $sorter): array
164
    {
165 4
        $sorter = array_intersect($sorter, array_keys($array));
166
167 4
        return array_merge(array_flip($sorter), $array);
168
    }
169
170
    /**
171
     * Recursively sorting an array by values.
172
     *
173
     * @param  array  $array
174
     * @param  callable|null  $callback
175
     *
176
     * @return array
177
     */
178 10
    public function sort(array $array, callable $callback = null): array
179
    {
180 10
        $callback = $callback ?: Sorter::default();
181
182 10
        usort($array, $callback);
183
184 10
        foreach ($array as &$value) {
185 10
            if (is_array($value)) {
186 8
                $value = $this->sort($value, $callback);
187
            }
188
        }
189
190 10
        return $array;
191
    }
192
193
    /**
194
     * Recursively sorting an array by keys.
195
     *
196
     * @param  array  $array
197
     * @param  callable|null  $callback
198
     *
199
     * @return array
200
     */
201 16
    public function ksort(array $array, callable $callback = null): array
202
    {
203 16
        $callback = $callback ?: Sorter::default();
204
205 16
        uksort($array, $callback);
206
207 16
        foreach ($array as &$value) {
208 16
            if (is_array($value)) {
209 10
                $value = $this->ksort($value, $callback);
210
            }
211
        }
212
213 16
        return $array;
214
    }
215
216
    /**
217
     * Merge one or more arrays recursively.
218
     * Don't forget that numeric keys NOT will be renumbered!
219
     *
220
     * @param  array[]  ...$arrays
221
     *
222
     * @return array
223
     */
224 160
    public function merge(...$arrays): array
225
    {
226 160
        $result = [];
227
228 160
        foreach ($arrays as $array) {
229 160
            foreach ($array as $key => $value) {
230 158
                if (is_array($value)) {
231 6
                    $value = $this->merge($result[$key] ?? [], $value);
232
                }
233
234 158
                $result[$key] = $value;
235
            }
236
        }
237
238 160
        return $result;
239
    }
240
241
    /**
242
     * If the given value is not an array and not null, wrap it in one.
243
     *
244
     * @param  mixed  $value
245
     *
246
     * @return array
247
     */
248 74
    public function wrap($value = null): array
249
    {
250 74
        if (is_array($value)) {
251 42
            return $value;
252
        }
253
254 46
        return ! empty($value) ? [$value] : [];
255
    }
256
257
    /**
258
     * Get the instance as an array.
259
     *
260
     * @param  mixed  $value
261
     *
262
     * @return array
263
     */
264 26
    public function toArray($value = null): array
265
    {
266 26
        if (InstanceHelper::of($value, [ArrayObject::class, ArrayableHelper::class])) {
267 2
            $value = CallHelper::runMethods($value, ['getArrayCopy', 'get']);
268
        }
269
270 26
        if (is_object($value)) {
271 16
            $value = method_exists($value, 'toArray') ? $value->toArray() : get_object_vars($value);
272
        }
273
274 26
        $array = $this->wrap($value);
275
276 26
        foreach ($array as &$item) {
277 26
            $item = $this->isArrayable($item) ? $this->toArray($item) : $item;
278
        }
279
280 26
        return $array;
281
    }
282
283
    /**
284
     * Determine if the given key exists in the provided array.
285
     *
286
     * @param  array|\ArrayAccess  $array
287
     * @param  mixed  $key
288
     *
289
     * @return bool
290
     */
291 4
    public function exists($array, $key): bool
292
    {
293 4
        if ($this->existsWithoutDot($array, $key)) {
294 4
            return true;
295
        }
296
297 4
        if (strpos($key, '.') === false) {
298 4
            return $this->existsWithoutDot($array, $key);
299
        }
300
301 2
        foreach (explode('.', $key) as $segment) {
302 2
            if ($this->isArrayable($array) && $this->exists($array, $segment)) {
303 2
                $array = $array[$segment];
304
            } else {
305 2
                return false;
306
            }
307
        }
308
309 2
        return true;
310
    }
311
312
    /**
313
     * Determine if the given key exists in the provided array without dot divider.
314
     *
315
     * @param  array|\ArrayAccess  $array
316
     * @param  mixed  $key
317
     *
318
     * @return bool
319
     */
320 211
    public function existsWithoutDot($array, $key): bool
321
    {
322 211
        if ($array instanceof ArrayAccess) {
323 6
            return $array->offsetExists($key);
324
        }
325
326 211
        return array_key_exists($key, $array);
327
    }
328
329
    /**
330
     * Get an item from an array.
331
     *
332
     * @see https://github.com/illuminate/collections/blob/master/Arr.php
333
     *
334
     * @param  array|ArrayAccess  $array
335
     * @param  mixed  $key
336
     * @param  mixed|null  $default
337
     *
338
     * @return mixed|null
339
     */
340 207
    public function get($array, $key, $default = null)
341
    {
342 207
        if (! $this->isArrayable($array)) {
343 2
            return $default;
344
        }
345
346 207
        if (is_null($key)) {
347 2
            return $array;
348
        }
349
350 207
        if ($this->existsWithoutDot($array, $key)) {
351 191
            return $array[$key];
352
        }
353
354 183
        if (strpos($key, '.') === false) {
355 183
            return $array[$key] ?? $default;
356
        }
357
358 2
        foreach (explode('.', $key) as $segment) {
359 2
            if ($this->isArrayable($array) && $this->existsWithoutDot($array, $segment)) {
360 2
                $array = $array[$segment];
361
            } else {
362 2
                return $default;
363
            }
364
        }
365
366 2
        return $array;
367
    }
368
369
    /**
370
     * If the element key exists, then return the name of the key, otherwise the default value.
371
     *
372
     * @param  array|ArrayAccess  $array
373
     * @param  mixed  $key
374
     * @param  mixed  $default
375
     *
376
     * @return mixed|null
377
     */
378 2
    public function getKey($array, $key, $default = null)
379
    {
380 2
        return $this->exists($array, $key) ? $key : $default;
381
    }
382
383
    /**
384
     * Get all of the given array except for a specified array of keys.
385
     *
386
     * @param  array|ArrayAccess  $array
387
     * @param  array|callable|string  $keys
388
     *
389
     * @return array
390
     */
391 10
    public function except($array, $keys): array
392
    {
393 10
        $callback = is_callable($keys)
394 6
            ? $keys
395 4
            : static function ($key) use ($keys) {
396 4
                return empty($keys) || ! in_array($key, (array) $keys);
397 10
            };
398
399 10
        return $this->filter((array) $array, $callback, ARRAY_FILTER_USE_KEY);
400
    }
401
402
    /**
403
     * Get a subset of the items from the given array.
404
     *
405
     * @param  array|ArrayAccess  $array
406
     * @param  array|callable|string  $keys
407
     *
408
     * @return array
409
     */
410 158
    public function only($array, $keys): array
411
    {
412 158
        if (is_callable($keys)) {
413 4
            return $this->filter($array, $keys, ARRAY_FILTER_USE_KEY);
414
        }
415
416 154
        $result = [];
417
418 154
        foreach ((array) $keys as $index => $key) {
419 154
            if (is_array($key) && isset($array[$index])) {
420 4
                $result[$index] = $this->only($array[$index], $key);
421 154
            } elseif (isset($array[$key])) {
422 152
                $result[$key] = $array[$key];
423
            }
424
        }
425
426 154
        return $result;
427
    }
428
429
    /**
430
     * Iterates over each value in the <b>array</b> passing them to the <b>callback</b> function.
431
     * If the <b>callback</b> function returns true, the current value from <b>array</b> is returned into
432
     * the result array. Array keys are preserved.
433
     *
434
     * @see https://php.net/manual/en/function.array-filter.php
435
     *
436
     * @param  array|ArrayAccess  $array
437
     * @param  callable|null  $callback
438
     * @param  int  $mode
439
     *
440
     * @return array
441
     */
442 41
    public function filter($array, callable $callback = null, int $mode = 0): array
443
    {
444 41
        if (empty($callback)) {
445 23
            $callback = $mode === ARRAY_FILTER_USE_BOTH
446
                ? Empties::notEmptyBoth()
447 23
                : Empties::notEmpty();
448
        }
449
450 41
        return array_filter($array, $callback, $mode);
0 ignored issues
show
Bug introduced by
It seems like $array can also be of type ArrayAccess; however, parameter $array of array_filter() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

450
        return array_filter(/** @scrutinizer ignore-type */ $array, $callback, $mode);
Loading history...
451
    }
452
453
    /**
454
     * Return all the keys or a subset of the keys of an array.
455
     *
456
     * @see https://php.net/manual/en/function.array-keys.php
457
     *
458
     * @param  mixed  $array
459
     *
460
     * @return array
461
     */
462 10
    public function keys($array): array
463
    {
464 10
        return array_keys($this->toArray($array));
465
    }
466
467
    /**
468
     * Return all the values of an array.
469
     *
470
     * @see  https://php.net/manual/en/function.array-values.php
471
     *
472
     * @param  mixed  $array
473
     *
474
     * @return array
475
     */
476 6
    public function values($array): array
477
    {
478 6
        return array_values($this->toArray($array));
479
    }
480
481
    /**
482
     * Exchanges all keys with their associated values in an array.
483
     *
484
     * @see  https://php.net/manual/en/function.array-flip.php
485
     *
486
     * @param  mixed  $array
487
     *
488
     * @return array
489
     */
490 10
    public function flip($array): array
491
    {
492 10
        return array_flip($this->toArray($array));
493
    }
494
495
    /**
496
     * Flatten a multi-dimensional array into a single level.
497
     *
498
     * @param  array  $array
499
     * @param  bool  $ignore_keys
500
     *
501
     * @return array
502
     */
503 10
    public function flatten(array $array, bool $ignore_keys = true): array
504
    {
505 10
        $result = [];
506
507 10
        foreach ($array as $key => $item) {
508 10
            if (! $this->isArrayable($item)) {
509 10
                $result = $ignore_keys
510 4
                    ? $this->push($result, $item)
511 10
                    : $this->set($result, $key, $item);
512
513 10
                continue;
514
            }
515
516 10
            $flatten = $this->flatten($item, $ignore_keys);
517
518 10
            $values = $ignore_keys ? array_values($flatten) : $flatten;
519
520 10
            $result = array_merge($result, $values);
521
        }
522
523 10
        return $ignore_keys ? array_values($result) : $result;
524
    }
525
526
    /**
527
     * Applies the callback to the elements of the given arrays.
528
     *
529
     * @param  array|ArrayAccess  $array
530
     * @param  callable  $callback
531
     * @param  bool  $recursive
532
     *
533
     * @return array
534
     */
535 96
    public function map($array, callable $callback, bool $recursive = false): array
536
    {
537 96
        foreach ($array as $key => &$value) {
538 96
            if ($recursive && is_array($value)) {
539 4
                $value = $this->map($value, $callback, $recursive);
540
            } else {
541 96
                $value = is_array($value) ? $value : $callback($value, $key);
542
            }
543
        }
544
545 96
        return $array;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $array could return the type ArrayAccess which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
546
    }
547
548
    /**
549
     * Push elements onto the end of array.
550
     *
551
     * @see  https://php.net/manual/en/function.array-push.php
552
     *
553
     * @param  array|ArrayAccess  $array
554
     * @param  mixed  ...$values
555
     *
556
     * @return array
557
     */
558 10
    public function push($array, ...$values): array
559
    {
560 10
        foreach ($values as $value) {
561 10
            array_push($array, $value);
562
        }
563
564 10
        return $array;
565
    }
566
567
    /**
568
     * Assigns a value to an array key.
569
     *
570
     * @param  array|ArrayAccess  $array
571
     * @param  mixed  $key
572
     * @param  mixed  $value
573
     *
574
     * @return array
575
     */
576 22
    public function set($array, $key, $value = null): array
577
    {
578 22
        if ($this->isArrayable($key)) {
579 4
            $array = $this->merge($array, $key);
0 ignored issues
show
Bug introduced by
It seems like $array can also be of type ArrayAccess; however, parameter $arrays of Helldar\Support\Helpers\Arr::merge() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

579
            $array = $this->merge(/** @scrutinizer ignore-type */ $array, $key);
Loading history...
580
        } else {
581 22
            $array[$key] = $value;
582
        }
583
584 22
        return $array;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $array could return the type ArrayAccess which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
585
    }
586
587
    /**
588
     * Removes an array key.
589
     *
590
     * @param  array|ArrayAccess  $array
591
     * @param  mixed  $key
592
     *
593
     * @return array
594
     */
595 6
    public function remove($array, $key): array
596
    {
597 6
        unset($array[$key]);
598
599 6
        return $array;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $array could return the type ArrayAccess which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
600
    }
601
602
    /**
603
     * Call the given Closure with the given value then return the value.
604
     *
605
     * @param  array|ArrayAccess  $array
606
     * @param  callable  $callback
607
     *
608
     * @return array
609
     */
610 4
    public function tap($array, callable $callback): array
611
    {
612 4
        foreach ($array as $key => &$value) {
613 4
            $callback($value, $key);
614
        }
615
616 4
        return $array;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $array could return the type ArrayAccess which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
617
    }
618
619
    /**
620
     * Check if the item is an array.
621
     *
622
     * @param  mixed  $value
623
     *
624
     * @return bool
625
     */
626 253
    public function isArrayable($value = null): bool
627
    {
628 253
        if (is_array($value) || is_object($value)) {
629 229
            return true;
630
        }
631
632 56
        return InstanceHelper::of($value, [ArrayAccess::class, Arrayable::class]);
633
    }
634
635
    /**
636
     * Determines if the array or arrayable object is empty.
637
     *
638
     * @param  mixed  $value
639
     *
640
     * @return bool
641
     */
642 8
    public function isEmpty($value): bool
643
    {
644 8
        $value = is_object($value) && method_exists($value, 'toArray') ? $value->toArray() : $value;
645 8
        $value = is_object($value) ? (array) $value : $value;
646
647 8
        return is_array($value) && empty($value);
648
    }
649
650
    /**
651
     * Determines if the value is doesn't empty.
652
     *
653
     * @param  mixed  $value
654
     *
655
     * @return bool
656
     */
657 2
    public function doesntEmpty($value): bool
658
    {
659 2
        return ! $this->isEmpty($value);
660
    }
661
662
    /**
663
     * Save array to php or json file.
664
     *
665
     * @param  array|ArrayAccess  $array
666
     * @param  string  $path
667
     * @param  bool  $is_json
668
     * @param  bool  $sort_keys
669
     * @param  int  $json_flags
670
     */
671 6
    public function store($array, string $path, bool $is_json = false, bool $sort_keys = false, int $json_flags = 0): void
672
    {
673 6
        $is_json
674 4
            ? $this->storeAsJson($path, $array, $sort_keys, $json_flags)
675 2
            : $this->storeAsArray($path, $array, $sort_keys);
676 6
    }
677
678
    /**
679
     * Save array to json file.
680
     *
681
     * @param  string  $path
682
     * @param  array|ArrayAccess  $array
683
     * @param  bool  $sort_keys
684
     * @param  int  $flags
685
     */
686 8
    public function storeAsJson(string $path, $array, bool $sort_keys = false, int $flags = 0): void
687
    {
688 8
        $this->prepareToStore($path, StubTool::JSON, $array, static function (array $array) use ($flags) {
0 ignored issues
show
Bug introduced by
It seems like $array can also be of type ArrayAccess; however, parameter $array of Helldar\Support\Helpers\Arr::prepareToStore() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

688
        $this->prepareToStore($path, StubTool::JSON, /** @scrutinizer ignore-type */ $array, static function (array $array) use ($flags) {
Loading history...
689 8
            return json_encode($array, $flags);
690 8
        }, $sort_keys);
691 8
    }
692
693
    /**
694
     * Save array to php file.
695
     *
696
     * @param  string  $path
697
     * @param  array|ArrayAccess  $array
698
     * @param  bool  $sort_keys
699
     */
700 4
    public function storeAsArray(string $path, $array, bool $sort_keys = false): void
701
    {
702 4
        $this->prepareToStore($path, StubTool::PHP_ARRAY, $array, static function (array $array) {
0 ignored issues
show
Bug introduced by
It seems like $array can also be of type ArrayAccess; however, parameter $array of Helldar\Support\Helpers\Arr::prepareToStore() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

702
        $this->prepareToStore($path, StubTool::PHP_ARRAY, /** @scrutinizer ignore-type */ $array, static function (array $array) {
Loading history...
703 4
            return var_export($array, true);
704 4
        }, $sort_keys);
705 4
    }
706
707
    /**
708
     * Prepare an array for writing to a file.
709
     *
710
     * @param  string  $path
711
     * @param  string  $stub
712
     * @param  array|ArrayAccess  $array
713
     * @param  callable  $replace
714
     * @param  bool  $sort_keys
715
     */
716 12
    protected function prepareToStore(string $path, string $stub, array $array, callable $replace, bool $sort_keys = false): void
717
    {
718 12
        $array = (array) $array;
719
720 12
        if ($sort_keys) {
721 6
            $this->ksort($array);
722
        }
723
724 12
        $content = Stub::replace($stub, [
725 12
            '{{slot}}' => $replace($array),
726
        ]);
727
728 12
        File::store($path, $content);
729 12
    }
730
}
731