Passed
Push — main ( 25f7f0...48e65d )
by Andrey
26:11 queued 24:40
created

Arr::only()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 11
c 1
b 0
f 0
nc 6
nop 2
dl 0
loc 19
ccs 12
cts 12
cp 1
crap 8
rs 8.4444
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 160
    public function only($array, $keys): array
411
    {
412 160
        if (is_callable($keys)) {
413 4
            return $this->filter($array, $keys, ARRAY_FILTER_USE_KEY);
414
        }
415
416 156
        $result = [];
417
418 156
        foreach ((array) $keys as $index => $key) {
419 156
            if (is_array($key) && isset($array[$index])) {
420 6
                $result[$index] = $this->only($array[$index], $key);
421 156
            } elseif (is_array($key) && ! isset($array[$index])) {
422 2
                continue;
423 156
            } elseif (isset($array[$key])) {
424 154
                $result[$key] = $array[$key];
425
            }
426
        }
427
428 156
        return $result;
429
    }
430
431
    /**
432
     * Iterates over each value in the <b>array</b> passing them to the <b>callback</b> function.
433
     * If the <b>callback</b> function returns true, the current value from <b>array</b> is returned into
434
     * the result array. Array keys are preserved.
435
     *
436
     * @see https://php.net/manual/en/function.array-filter.php
437
     *
438
     * @param  array|ArrayAccess  $array
439
     * @param  callable|null  $callback
440
     * @param  int  $mode
441
     *
442
     * @return array
443
     */
444 41
    public function filter($array, callable $callback = null, int $mode = 0): array
445
    {
446 41
        if (empty($callback)) {
447 23
            $callback = $mode === ARRAY_FILTER_USE_BOTH
448
                ? Empties::notEmptyBoth()
449 23
                : Empties::notEmpty();
450
        }
451
452 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

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

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

690
        $this->prepareToStore($path, StubTool::JSON, /** @scrutinizer ignore-type */ $array, static function (array $array) use ($flags) {
Loading history...
691 8
            return json_encode($array, $flags);
692 8
        }, $sort_keys);
693 8
    }
694
695
    /**
696
     * Save array to php file.
697
     *
698
     * @param  string  $path
699
     * @param  array|ArrayAccess  $array
700
     * @param  bool  $sort_keys
701
     */
702 4
    public function storeAsArray(string $path, $array, bool $sort_keys = false): void
703
    {
704 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

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