Passed
Pull Request — main (#161)
by Andrey
11:13
created

Arr::only()   B

Complexity

Conditions 9
Paths 9

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 9

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 9
eloc 17
c 2
b 1
f 0
nc 9
nop 2
dl 0
loc 27
ccs 10
cts 10
cp 1
crap 9
rs 8.0555
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
            try {
420 4
                if (is_array($key) && isset($array[$index])) {
421 154
                    $result[$index] = $this->only($array[$index], $key);
422 152
                } elseif (is_array($key) && ! isset($array[$index])) {
423
                    continue;
424
                } elseif (isset($array[$key])) {
425
                    $result[$key] = $array[$key];
426 154
                }
427
            } catch (\Throwable$e) {
428
                dd(
429
                    $e->getMessage(),
430
                    $index,
431
                    $key
432
                );
433
            }
434
        }
435
436
        return $result;
437
    }
438
439
    /**
440
     * Iterates over each value in the <b>array</b> passing them to the <b>callback</b> function.
441
     * If the <b>callback</b> function returns true, the current value from <b>array</b> is returned into
442 41
     * the result array. Array keys are preserved.
443
     *
444 41
     * @see https://php.net/manual/en/function.array-filter.php
445 23
     *
446
     * @param  array|ArrayAccess  $array
447 23
     * @param  callable|null  $callback
448
     * @param  int  $mode
449
     *
450 41
     * @return array
451
     */
452
    public function filter($array, callable $callback = null, int $mode = 0): array
453
    {
454
        if (empty($callback)) {
455
            $callback = $mode === ARRAY_FILTER_USE_BOTH
456
                ? Empties::notEmptyBoth()
457
                : Empties::notEmpty();
458
        }
459
460
        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

460
        return array_filter(/** @scrutinizer ignore-type */ $array, $callback, $mode);
Loading history...
461
    }
462 10
463
    /**
464 10
     * Return all the keys or a subset of the keys of an array.
465
     *
466
     * @see https://php.net/manual/en/function.array-keys.php
467
     *
468
     * @param  mixed  $array
469
     *
470
     * @return array
471
     */
472
    public function keys($array): array
473
    {
474
        return array_keys($this->toArray($array));
475
    }
476 6
477
    /**
478 6
     * Return all the values of an array.
479
     *
480
     * @see  https://php.net/manual/en/function.array-values.php
481
     *
482
     * @param  mixed  $array
483
     *
484
     * @return array
485
     */
486
    public function values($array): array
487
    {
488
        return array_values($this->toArray($array));
489
    }
490 10
491
    /**
492 10
     * Exchanges all keys with their associated values in an array.
493
     *
494
     * @see  https://php.net/manual/en/function.array-flip.php
495
     *
496
     * @param  mixed  $array
497
     *
498
     * @return array
499
     */
500
    public function flip($array): array
501
    {
502
        return array_flip($this->toArray($array));
503 10
    }
504
505 10
    /**
506
     * Flatten a multi-dimensional array into a single level.
507 10
     *
508 10
     * @param  array  $array
509 10
     * @param  bool  $ignore_keys
510 4
     *
511 10
     * @return array
512
     */
513 10
    public function flatten(array $array, bool $ignore_keys = true): array
514
    {
515
        $result = [];
516 10
517
        foreach ($array as $key => $item) {
518 10
            if (! $this->isArrayable($item)) {
519
                $result = $ignore_keys
520 10
                    ? $this->push($result, $item)
521
                    : $this->set($result, $key, $item);
522
523 10
                continue;
524
            }
525
526
            $flatten = $this->flatten($item, $ignore_keys);
527
528
            $values = $ignore_keys ? array_values($flatten) : $flatten;
529
530
            $result = array_merge($result, $values);
531
        }
532
533
        return $ignore_keys ? array_values($result) : $result;
534
    }
535 96
536
    /**
537 96
     * Applies the callback to the elements of the given arrays.
538 96
     *
539 4
     * @param  array|ArrayAccess  $array
540
     * @param  callable  $callback
541 96
     * @param  bool  $recursive
542
     *
543
     * @return array
544
     */
545 96
    public function map($array, callable $callback, bool $recursive = false): array
546
    {
547
        foreach ($array as $key => &$value) {
548
            if ($recursive && is_array($value)) {
549
                $value = $this->map($value, $callback, $recursive);
550
            } else {
551
                $value = is_array($value) ? $value : $callback($value, $key);
552
            }
553
        }
554
555
        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...
556
    }
557
558 10
    /**
559
     * Push elements onto the end of array.
560 10
     *
561 10
     * @see  https://php.net/manual/en/function.array-push.php
562
     *
563
     * @param  array|ArrayAccess  $array
564 10
     * @param  mixed  ...$values
565
     *
566
     * @return array
567
     */
568
    public function push($array, ...$values): array
569
    {
570
        foreach ($values as $value) {
571
            array_push($array, $value);
572
        }
573
574
        return $array;
575
    }
576 22
577
    /**
578 22
     * Assigns a value to an array key.
579 4
     *
580
     * @param  array|ArrayAccess  $array
581 22
     * @param  mixed  $key
582
     * @param  mixed  $value
583
     *
584 22
     * @return array
585
     */
586
    public function set($array, $key, $value = null): array
587
    {
588
        if ($this->isArrayable($key)) {
589
            $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

589
            $array = $this->merge(/** @scrutinizer ignore-type */ $array, $key);
Loading history...
590
        } else {
591
            $array[$key] = $value;
592
        }
593
594
        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...
595 6
    }
596
597 6
    /**
598
     * Removes an array key.
599 6
     *
600
     * @param  array|ArrayAccess  $array
601
     * @param  mixed  $key
602
     *
603
     * @return array
604
     */
605
    public function remove($array, $key): array
606
    {
607
        unset($array[$key]);
608
609
        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...
610 4
    }
611
612 4
    /**
613 4
     * Call the given Closure with the given value then return the value.
614
     *
615
     * @param  array|ArrayAccess  $array
616 4
     * @param  callable  $callback
617
     *
618
     * @return array
619
     */
620
    public function tap($array, callable $callback): array
621
    {
622
        foreach ($array as $key => &$value) {
623
            $callback($value, $key);
624
        }
625
626 253
        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...
627
    }
628 253
629 229
    /**
630
     * Check if the item is an array.
631
     *
632 56
     * @param  mixed  $value
633
     *
634
     * @return bool
635
     */
636
    public function isArrayable($value = null): bool
637
    {
638
        if (is_array($value) || is_object($value)) {
639
            return true;
640
        }
641
642 8
        return InstanceHelper::of($value, [ArrayAccess::class, Arrayable::class]);
643
    }
644 8
645 8
    /**
646
     * Determines if the array or arrayable object is empty.
647 8
     *
648
     * @param  mixed  $value
649
     *
650
     * @return bool
651
     */
652
    public function isEmpty($value): bool
653
    {
654
        $value = is_object($value) && method_exists($value, 'toArray') ? $value->toArray() : $value;
655
        $value = is_object($value) ? (array) $value : $value;
656
657 2
        return is_array($value) && empty($value);
658
    }
659 2
660
    /**
661
     * Determines if the value is doesn't empty.
662
     *
663
     * @param  mixed  $value
664
     *
665
     * @return bool
666
     */
667
    public function doesntEmpty($value): bool
668
    {
669
        return ! $this->isEmpty($value);
670
    }
671 6
672
    /**
673 6
     * Save array to php or json file.
674 4
     *
675 2
     * @param  array|ArrayAccess  $array
676 6
     * @param  string  $path
677
     * @param  bool  $is_json
678
     * @param  bool  $sort_keys
679
     * @param  int  $json_flags
680
     */
681
    public function store($array, string $path, bool $is_json = false, bool $sort_keys = false, int $json_flags = 0): void
682
    {
683
        $is_json
684
            ? $this->storeAsJson($path, $array, $sort_keys, $json_flags)
685
            : $this->storeAsArray($path, $array, $sort_keys);
686 8
    }
687
688 8
    /**
689 8
     * Save array to json file.
690 8
     *
691 8
     * @param  string  $path
692
     * @param  array|ArrayAccess  $array
693
     * @param  bool  $sort_keys
694
     * @param  int  $flags
695
     */
696
    public function storeAsJson(string $path, $array, bool $sort_keys = false, int $flags = 0): void
697
    {
698
        $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

698
        $this->prepareToStore($path, StubTool::JSON, /** @scrutinizer ignore-type */ $array, static function (array $array) use ($flags) {
Loading history...
699
            return json_encode($array, $flags);
700 4
        }, $sort_keys);
701
    }
702 4
703 4
    /**
704 4
     * Save array to php file.
705 4
     *
706
     * @param  string  $path
707
     * @param  array|ArrayAccess  $array
708
     * @param  bool  $sort_keys
709
     */
710
    public function storeAsArray(string $path, $array, bool $sort_keys = false): void
711
    {
712
        $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

712
        $this->prepareToStore($path, StubTool::PHP_ARRAY, /** @scrutinizer ignore-type */ $array, static function (array $array) {
Loading history...
713
            return var_export($array, true);
714
        }, $sort_keys);
715
    }
716 12
717
    /**
718 12
     * Prepare an array for writing to a file.
719
     *
720 12
     * @param  string  $path
721 6
     * @param  string  $stub
722
     * @param  array|ArrayAccess  $array
723
     * @param  callable  $replace
724 12
     * @param  bool  $sort_keys
725 12
     */
726
    protected function prepareToStore(string $path, string $stub, array $array, callable $replace, bool $sort_keys = false): void
727
    {
728 12
        $array = (array) $array;
729 12
730
        if ($sort_keys) {
731
            $this->ksort($array);
732
        }
733
734
        $content = Stub::replace($stub, [
735
            '{{slot}}' => $replace($array),
736
        ]);
737
738
        File::store($path, $content);
739
    }
740
}
741