Passed
Pull Request — main (#156)
by Andrey
15:08 queued 15s
created

Arr::exists()   B

Complexity

Conditions 9
Paths 7

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 14
c 1
b 0
f 0
nc 7
nop 2
dl 0
loc 27
ccs 8
cts 8
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 Helldar\Contracts\Support\Arrayable;
21
use Helldar\Support\Facades\Callbacks\Empties;
22
use Helldar\Support\Facades\Callbacks\Sorter;
23
use Helldar\Support\Facades\Helpers\Filesystem\File;
24
use Helldar\Support\Facades\Helpers\Instance as InstanceHelper;
25
use Helldar\Support\Facades\Tools\Stub;
26
use Helldar\Support\Helpers\Ables\Arrayable as ArrayableHelper;
27
use Helldar\Support\Tools\Stub as StubTool;
28
29
class Arr
30
{
31
    /**
32
     * Get a new arrayable object from the given array.
33
     *
34
     * @param  array|ArrayAccess|string|null  $value
35
     *
36
     * @return \Helldar\Support\Helpers\Ables\Arrayable
37
     */
38 1
    public function of($value = []): Ables\Arrayable
39
    {
40 1
        return new Ables\Arrayable($value);
41
    }
42
43
    /**
44
     * Renaming array keys.
45
     * As the second parameter, a callback function is passed, which determines the actions for processing the value.
46
     * The output of the function must be a string with a name.
47
     *
48
     * @param  array  $array
49
     * @param  callable  $callback
50
     *
51
     * @return array
52
     */
53 10
    public function renameKeys(array $array, callable $callback): array
54
    {
55 10
        $result = [];
56
57 10
        foreach ($array as $key => $value) {
58 10
            $new = $callback($key, $value);
59
60 10
            $result[$new] = $value;
61
        }
62
63 10
        return $result;
64
    }
65
66
    /**
67
     * Renaming array keys with map.
68
     *
69
     * @param  array  $array
70
     * @param  array  $map
71
     *
72
     * @return array
73
     */
74 4
    public function renameKeysMap(array $array, array $map): array
75
    {
76 4
        return $this->renameKeys($array, static function ($key) use ($map) {
77 4
            return $map[$key] ?? $key;
78 4
        });
79
    }
80
81
    /**
82
     * Get the size of the longest text element of the array.
83
     *
84
     * @param  array  $array
85
     *
86
     * @return int
87
     */
88 2
    public function longestStringLength(array $array): int
89
    {
90 2
        return ! empty($array) ? max(array_map('mb_strlen', $array)) : 0;
91
    }
92
93
    /**
94
     * Push one a unique element onto the end of array.
95
     *
96
     * @param  array  $array
97
     * @param  mixed  $values
98
     *
99
     * @return array
100
     */
101 6
    public function addUnique(array $array, $values): array
102
    {
103 6
        if ($this->isArrayable($values)) {
104 6
            foreach ($values as $value) {
105 6
                $array = $this->addUnique($array, $value);
106
            }
107
        } else {
108 6
            array_push($array, $values);
109
        }
110
111 6
        return $this->unique($array);
112
    }
113
114
    /**
115
     * Removes duplicate values from an array.
116
     *
117
     * Sorting type flags:
118
     *   SORT_REGULAR       - compare items normally
119
     *   SORT_NUMERIC       - compare items numerically
120
     *   SORT_STRING        - compare items as strings
121
     *   SORT_LOCALE_STRING - compare items as strings, based on the current locale
122
     *
123
     * @see https://php.net/manual/en/function.array-unique.php
124
     *
125
     * @param  array  $array
126
     * @param  int  $flags
127
     *
128
     * @return array
129
     */
130 10
    public function unique(array $array, int $flags = SORT_STRING): array
131
    {
132 10
        return array_unique($array, $flags);
133
    }
134
135
    /**
136
     * Sort an associative array in the order specified by an array of keys.
137
     *
138
     * Example:
139
     *
140
     *  $arr = ['q' => 1, 'r' => 2, 's' => 5, 'w' => 123];
141
     *
142
     *  Arr::sortByKeys($arr, ['q', 'w', 'e']);
143
     *
144
     * print_r($arr);
145
     *
146
     *   Array
147
     *   (
148
     *     [q] => 1
149
     *     [w] => 123
150
     *     [r] => 2
151
     *     [s] => 5
152
     *   )
153
     *
154
     * @see https://gist.github.com/Ellrion/a3145621f936aa9416f4c04987533d8d#file-helper-php
155
     *
156
     * @param  array  $array
157
     * @param  array  $sorter
158
     *
159
     * @return array
160
     */
161 4
    public function sortByKeys(array $array, array $sorter): array
162
    {
163 4
        $sorter = array_intersect($sorter, array_keys($array));
164
165 4
        return array_merge(array_flip($sorter), $array);
166
    }
167
168
    /**
169
     * Recursively sorting an array by values.
170
     *
171
     * @param  array  $array
172
     * @param  callable|null  $callback
173
     *
174
     * @return array
175
     */
176 10
    public function sort(array $array, callable $callback = null): array
177
    {
178 10
        $callback = $callback ?: Sorter::default();
179
180 10
        usort($array, $callback);
181
182 10
        foreach ($array as &$value) {
183 10
            if (is_array($value)) {
184 8
                $value = $this->sort($value, $callback);
185
            }
186
        }
187
188 10
        return $array;
189
    }
190
191
    /**
192
     * Recursively sorting an array by keys.
193
     *
194
     * @param  array  $array
195
     * @param  callable|null  $callback
196
     *
197
     * @return array
198
     */
199 16
    public function ksort(array $array, callable $callback = null): array
200
    {
201 16
        $callback = $callback ?: Sorter::default();
202
203 16
        uksort($array, $callback);
204
205 16
        foreach ($array as &$value) {
206 16
            if (is_array($value)) {
207 10
                $value = $this->ksort($value, $callback);
208
            }
209
        }
210
211 16
        return $array;
212
    }
213
214
    /**
215
     * Merge one or more arrays recursively.
216
     * Don't forget that numeric keys NOT will be renumbered!
217
     *
218
     * @param  array[]  ...$arrays
219
     *
220
     * @return array
221
     */
222 160
    public function merge(...$arrays): array
223
    {
224 160
        $result = [];
225
226 160
        foreach ($arrays as $array) {
227 160
            foreach ($array as $key => $value) {
228 158
                if (is_array($value)) {
229 6
                    $value = $this->merge($result[$key] ?? [], $value);
230
                }
231
232 158
                $result[$key] = $value;
233
            }
234
        }
235
236 160
        return $result;
237
    }
238
239
    /**
240
     * If the given value is not an array and not null, wrap it in one.
241
     *
242
     * @param  mixed  $value
243
     *
244
     * @return array
245
     */
246 74
    public function wrap($value = null): array
247
    {
248 74
        if (is_array($value)) {
249 42
            return $value;
250
        }
251
252 58
        return ! empty($value) ? [$value] : [];
253
    }
254
255
    /**
256
     * Get the instance as an array.
257
     *
258
     * @param  mixed  $value
259
     *
260
     * @return array
261
     */
262 26
    public function toArray($value = null): array
263
    {
264 26
        if (InstanceHelper::of($value, ArrayableHelper::class)) {
265 2
            $value = $value->get();
0 ignored issues
show
Bug introduced by
The method get() does not exist on null. ( Ignorable by Annotation )

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

265
            /** @scrutinizer ignore-call */ 
266
            $value = $value->get();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
266
        }
267
268 26
        if (is_object($value)) {
269 16
            $value = method_exists($value, 'toArray') ? $value->toArray() : get_object_vars($value);
270
        }
271
272 26
        $array = $this->wrap($value);
273
274 26
        foreach ($array as &$item) {
275 26
            $item = $this->isArrayable($item) ? $this->toArray($item) : $item;
276
        }
277
278 26
        return $array;
279
    }
280
281
    /**
282
     * Determine if the given key exists in the provided array.
283
     *
284
     * @param  array|\ArrayAccess  $array
285
     * @param  mixed  $key
286
     *
287
     * @return bool
288
     */
289 209
    public function exists($array, $key): bool
290
    {
291 209
        if ($array instanceof ArrayAccess) {
292 4
            return $array->offsetExists($key);
293
        }
294
295 209
        if (! $this->isArrayable($array) || empty($array)) {
296
            return false;
297
        }
298
299
        if (array_key_exists($key, $array)) {
300
            return true;
301
        }
302
303
        if (strpos($key, '.') === false) {
304
            return array_key_exists($key, $array);
305
        }
306
307
        foreach (explode('.', $key) as $segment) {
308
            if ($this->isArrayable($array) && $this->exists($array, $segment)) {
309 207
                $array = $array[$segment];
310
            } else {
311 207
                return false;
312 2
            }
313
        }
314
315 207
        return true;
316 2
    }
317
318
    /**
319 207
     * Get an item from an array.
320 191
     *
321
     * @see https://github.com/illuminate/collections/blob/master/Arr.php
322
     *
323 183
     * @param  array|ArrayAccess  $array
324 183
     * @param  mixed  $key
325
     * @param  mixed|null  $default
326
     *
327 2
     * @return mixed|null
328 2
     */
329 2
    public function get($array, $key, $default = null)
330
    {
331 2
        if (! $this->isArrayable($array)) {
332
            return $default;
333
        }
334
335 2
        if (is_null($key)) {
336
            return $array;
337
        }
338
339
        if (array_key_exists($key, $array)) {
340
            return $array[$key];
341
        }
342
343
        if (strpos($key, '.') === false) {
344
            return $array[$key] ?? $default;
345
        }
346
347 2
        foreach (explode('.', $key) as $segment) {
348
            if ($this->isArrayable($array) && $this->exists($array, $segment)) {
349 2
                $array = $array[$segment];
350
            } else {
351
                return $default;
352
            }
353
        }
354
355
        return $array;
356
    }
357
358
    /**
359
     * If the element key exists, then return the name of the key, otherwise the default value.
360 10
     *
361
     * @param  array|ArrayAccess  $array
362 10
     * @param  mixed  $key
363 6
     * @param  mixed  $default
364 4
     *
365 4
     * @return mixed|null
366 10
     */
367
    public function getKey($array, $key, $default = null)
368 10
    {
369
        return $this->exists($array, $key) ? $key : $default;
370
    }
371
372
    /**
373
     * Get all of the given array except for a specified array of keys.
374
     *
375
     * @param  array|ArrayAccess  $array
376
     * @param  array|callable|string  $keys
377
     *
378
     * @return array
379 158
     */
380
    public function except($array, $keys): array
381 158
    {
382 4
        $callback = is_callable($keys)
383
            ? $keys
384
            : static function ($key) use ($keys) {
385 154
                return empty($keys) || ! in_array($key, (array) $keys);
386
            };
387 154
388 154
        return $this->filter((array) $array, $callback, ARRAY_FILTER_USE_KEY);
389 4
    }
390 154
391 152
    /**
392
     * Get a subset of the items from the given array.
393
     *
394
     * @param  array|ArrayAccess  $array
395 154
     * @param  array|callable|string  $keys
396
     *
397
     * @return array
398
     */
399
    public function only($array, $keys): array
400
    {
401
        if (is_callable($keys)) {
402
            return $this->filter($array, $keys, ARRAY_FILTER_USE_KEY);
403
        }
404
405
        $result = [];
406
407
        foreach ((array) $keys as $index => $key) {
408
            if (is_array($key) && isset($array[$index])) {
409
                $result[$index] = $this->only($array[$index], $key);
410
            } elseif (isset($array[$key])) {
411 41
                $result[$key] = $array[$key];
412
            }
413 41
        }
414 23
415
        return $result;
416 23
    }
417
418
    /**
419 41
     * Iterates over each value in the <b>array</b> passing them to the <b>callback</b> function.
420
     * If the <b>callback</b> function returns true, the current value from <b>array</b> is returned into
421
     * the result array. Array keys are preserved.
422
     *
423
     * @see https://php.net/manual/en/function.array-filter.php
424
     *
425
     * @param  array|ArrayAccess  $array
426
     * @param  callable|null  $callback
427
     * @param  int  $mode
428
     *
429
     * @return array
430
     */
431 10
    public function filter($array, callable $callback = null, int $mode = 0): array
432
    {
433 10
        if (empty($callback)) {
434
            $callback = $mode === ARRAY_FILTER_USE_BOTH
435
                ? Empties::notEmptyBoth()
436
                : Empties::notEmpty();
437
        }
438
439
        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

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

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

677
        $this->prepareToStore($path, StubTool::JSON, /** @scrutinizer ignore-type */ $array, static function (array $array) use ($flags) {
Loading history...
678
            return json_encode($array, $flags);
679
        }, $sort_keys);
680
    }
681
682
    /**
683
     * Save array to php file.
684
     *
685 12
     * @param  string  $path
686
     * @param  array|ArrayAccess  $array
687 12
     * @param  bool  $sort_keys
688
     */
689 12
    public function storeAsArray(string $path, $array, bool $sort_keys = false): void
690 6
    {
691
        $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

691
        $this->prepareToStore($path, StubTool::PHP_ARRAY, /** @scrutinizer ignore-type */ $array, static function (array $array) {
Loading history...
692
            return var_export($array, true);
693 12
        }, $sort_keys);
694 12
    }
695
696
    /**
697 12
     * Prepare an array for writing to a file.
698 12
     *
699
     * @param  string  $path
700
     * @param  string  $stub
701
     * @param  array|ArrayAccess  $array
702
     * @param  callable  $replace
703
     * @param  bool  $sort_keys
704
     */
705
    protected function prepareToStore(string $path, string $stub, array $array, callable $replace, bool $sort_keys = false): void
706
    {
707
        $array = (array) $array;
708
709
        if ($sort_keys) {
710
            $this->ksort($array);
711
        }
712
713
        $content = Stub::replace($stub, [
714
            '{{slot}}' => $replace($array),
715
        ]);
716
717
        File::store($path, $content);
718
    }
719
}
720