Passed
Pull Request — main (#156)
by Andrey
13:57
created

Arr::existsWithoutDot()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 7
ccs 3
cts 3
cp 1
crap 2
rs 10
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 1
     * @return \Helldar\Support\Helpers\Ables\Arrayable
39
     */
40 1
    public function of($value = []): Ables\Arrayable
41
    {
42
        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 10
     * @return array
54
     */
55 10
    public function renameKeys(array $array, callable $callback): array
56
    {
57 10
        $result = [];
58 10
59
        foreach ($array as $key => $value) {
60 10
            $new = $callback($key, $value);
61
62
            $result[$new] = $value;
63 10
        }
64
65
        return $result;
66
    }
67
68
    /**
69
     * Renaming array keys with map.
70
     *
71
     * @param  array  $array
72
     * @param  array  $map
73
     *
74 4
     * @return array
75
     */
76 4
    public function renameKeysMap(array $array, array $map): array
77 4
    {
78 4
        return $this->renameKeys($array, static function ($key) use ($map) {
79
            return $map[$key] ?? $key;
80
        });
81
    }
82
83
    /**
84
     * Get the size of the longest text element of the array.
85
     *
86
     * @param  array  $array
87
     *
88 2
     * @return int
89
     */
90 2
    public function longestStringLength(array $array): int
91
    {
92
        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 6
     * @return array
102
     */
103 6
    public function addUnique(array $array, $values): array
104 6
    {
105 6
        if ($this->isArrayable($values)) {
106
            foreach ($values as $value) {
107
                $array = $this->addUnique($array, $value);
108 6
            }
109
        } else {
110
            array_push($array, $values);
111 6
        }
112
113
        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 10
     * @return array
131
     */
132 10
    public function unique(array $array, int $flags = SORT_STRING): array
133
    {
134
        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 4
     * @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
        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 10
     * @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 10
184 8
        foreach ($array as &$value) {
185
            if (is_array($value)) {
186
                $value = $this->sort($value, $callback);
187
            }
188 10
        }
189
190
        return $array;
191
    }
192
193
    /**
194
     * Recursively sorting an array by keys.
195
     *
196
     * @param  array  $array
197
     * @param  callable|null  $callback
198
     *
199 16
     * @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 16
207 10
        foreach ($array as &$value) {
208
            if (is_array($value)) {
209
                $value = $this->ksort($value, $callback);
210
            }
211 16
        }
212
213
        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 160
     * @return array
223
     */
224 160
    public function merge(...$arrays): array
225
    {
226 160
        $result = [];
227 160
228 158
        foreach ($arrays as $array) {
229 6
            foreach ($array as $key => $value) {
230
                if (is_array($value)) {
231
                    $value = $this->merge($result[$key] ?? [], $value);
232 158
                }
233
234
                $result[$key] = $value;
235
            }
236 160
        }
237
238
        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 74
     * @return array
247
     */
248 74
    public function wrap($value = null): array
249 42
    {
250
        if (is_array($value)) {
251
            return $value;
252 58
        }
253
254
        return ! empty($value) ? [$value] : [];
255
    }
256
257
    /**
258
     * Get the instance as an array.
259
     *
260
     * @param  mixed  $value
261
     *
262 26
     * @return array
263
     */
264 26
    public function toArray($value = null): array
265 2
    {
266
        if (InstanceHelper::of($value, [ArrayObject::class, ArrayableHelper::class])) {
267
            $value = CallHelper::runMethods($value, ['getArrayCopy', 'get']);
268 26
        }
269 16
270
        if (is_object($value)) {
271
            $value = method_exists($value, 'toArray') ? $value->toArray() : get_object_vars($value);
272 26
        }
273
274 26
        $array = $this->wrap($value);
275 26
276
        foreach ($array as &$item) {
277
            $item = $this->isArrayable($item) ? $this->toArray($item) : $item;
278 26
        }
279
280
        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 209
     * @return bool
290
     */
291 209
    public function exists($array, $key): bool
292 4
    {
293
        if ($this->existsWithoutDot($array, $key)) {
294
            return true;
295 209
        }
296
297
        if (strpos($key, '.') === false) {
298
            return $this->existsWithoutDot($array, $key);
299
        }
300
301
        foreach (explode('.', $key) as $segment) {
302
            if ($this->isArrayable($array) && $this->exists($array, $segment)) {
303
                $array = $array[$segment];
304
            } else {
305
                return false;
306
            }
307
        }
308
309 207
        return true;
310
    }
311 207
312 2
    /**
313
     * Determine if the given key exists in the provided array without dot divider.
314
     *
315 207
     * @param  array|\ArrayAccess  $array
316 2
     * @param  mixed  $key
317
     *
318
     * @return bool
319 207
     */
320 191
    public function existsWithoutDot($array, $key): bool
321
    {
322
        if ($array instanceof ArrayAccess) {
323 183
            return $array->offsetExists($key);
324 183
        }
325
326
        return array_key_exists($key, $array);
327 2
    }
328 2
329 2
    /**
330
     * Get an item from an array.
331 2
     *
332
     * @see https://github.com/illuminate/collections/blob/master/Arr.php
333
     *
334
     * @param  array|ArrayAccess  $array
335 2
     * @param  mixed  $key
336
     * @param  mixed|null  $default
337
     *
338
     * @return mixed|null
339
     */
340
    public function get($array, $key, $default = null)
341
    {
342
        if (! $this->isArrayable($array)) {
343
            return $default;
344
        }
345
346
        if (is_null($key)) {
347 2
            return $array;
348
        }
349 2
350
        if ($this->existsWithoutDot($array, $key)) {
351
            return $array[$key];
352
        }
353
354
        if (strpos($key, '.') === false) {
355
            return $array[$key] ?? $default;
356
        }
357
358
        foreach (explode('.', $key) as $segment) {
359
            if ($this->isArrayable($array) && $this->existsWithoutDot($array, $segment)) {
360 10
                $array = $array[$segment];
361
            } else {
362 10
                return $default;
363 6
            }
364 4
        }
365 4
366 10
        return $array;
367
    }
368 10
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
    public function getKey($array, $key, $default = null)
379 158
    {
380
        return $this->exists($array, $key) ? $key : $default;
381 158
    }
382 4
383
    /**
384
     * Get all of the given array except for a specified array of keys.
385 154
     *
386
     * @param  array|ArrayAccess  $array
387 154
     * @param  array|callable|string  $keys
388 154
     *
389 4
     * @return array
390 154
     */
391 152
    public function except($array, $keys): array
392
    {
393
        $callback = is_callable($keys)
394
            ? $keys
395 154
            : static function ($key) use ($keys) {
396
                return empty($keys) || ! in_array($key, (array) $keys);
397
            };
398
399
        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
    public function only($array, $keys): array
411 41
    {
412
        if (is_callable($keys)) {
413 41
            return $this->filter($array, $keys, ARRAY_FILTER_USE_KEY);
414 23
        }
415
416 23
        $result = [];
417
418
        foreach ((array) $keys as $index => $key) {
419 41
            if (is_array($key) && isset($array[$index])) {
420
                $result[$index] = $this->only($array[$index], $key);
421
            } elseif (isset($array[$key])) {
422
                $result[$key] = $array[$key];
423
            }
424
        }
425
426
        return $result;
427
    }
428
429
    /**
430
     * Iterates over each value in the <b>array</b> passing them to the <b>callback</b> function.
431 10
     * 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 10
     *
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
    public function filter($array, callable $callback = null, int $mode = 0): array
443
    {
444
        if (empty($callback)) {
445 6
            $callback = $mode === ARRAY_FILTER_USE_BOTH
446
                ? Empties::notEmptyBoth()
447 6
                : Empties::notEmpty();
448
        }
449
450
        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 10
     *
460
     * @return array
461 10
     */
462
    public function keys($array): array
463
    {
464
        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 10
     * @param  mixed  $array
473
     *
474 10
     * @return array
475
     */
476 10
    public function values($array): array
477 10
    {
478 10
        return array_values($this->toArray($array));
479 4
    }
480 10
481
    /**
482 10
     * Exchanges all keys with their associated values in an array.
483
     *
484
     * @see  https://php.net/manual/en/function.array-flip.php
485 10
     *
486
     * @param  mixed  $array
487 10
     *
488
     * @return array
489 10
     */
490
    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
    public function flatten(array $array, bool $ignore_keys = true): array
504 96
    {
505
        $result = [];
506 96
507 96
        foreach ($array as $key => $item) {
508 4
            if (! $this->isArrayable($item)) {
509
                $result = $ignore_keys
510 96
                    ? $this->push($result, $item)
511
                    : $this->set($result, $key, $item);
512
513
                continue;
514 96
            }
515
516
            $flatten = $this->flatten($item, $ignore_keys);
517
518
            $values = $ignore_keys ? array_values($flatten) : $flatten;
519
520
            $result = array_merge($result, $values);
521
        }
522
523
        return $ignore_keys ? array_values($result) : $result;
524
    }
525
526
    /**
527 10
     * Applies the callback to the elements of the given arrays.
528
     *
529 10
     * @param  array|ArrayAccess  $array
530 10
     * @param  callable  $callback
531
     * @param  bool  $recursive
532
     *
533 10
     * @return array
534
     */
535
    public function map($array, callable $callback, bool $recursive = false): array
536
    {
537
        foreach ($array as $key => &$value) {
538
            if ($recursive && is_array($value)) {
539
                $value = $this->map($value, $callback, $recursive);
540
            } else {
541
                $value = is_array($value) ? $value : $callback($value, $key);
542
            }
543
        }
544
545 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...
546
    }
547 22
548 4
    /**
549
     * Push elements onto the end of array.
550 22
     *
551
     * @see  https://php.net/manual/en/function.array-push.php
552
     *
553 22
     * @param  array|ArrayAccess  $array
554
     * @param  mixed  ...$values
555
     *
556
     * @return array
557
     */
558
    public function push($array, ...$values): array
559
    {
560
        foreach ($values as $value) {
561
            array_push($array, $value);
562
        }
563
564 6
        return $array;
565
    }
566 6
567
    /**
568 6
     * 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
    public function set($array, $key, $value = null): array
577
    {
578
        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 4
            $array[$key] = $value;
582 4
        }
583
584
        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 4
    }
586
587
    /**
588
     * Removes an array key.
589
     *
590
     * @param  array|ArrayAccess  $array
591
     * @param  mixed  $key
592
     *
593
     * @return array
594
     */
595 251
    public function remove($array, $key): array
596
    {
597 251
        unset($array[$key]);
598 227
599
        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 56
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
    public function tap($array, callable $callback): array
611 8
    {
612
        foreach ($array as $key => &$value) {
613 8
            $callback($value, $key);
614 8
        }
615
616 8
        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 2
    public function isArrayable($value = null): bool
627
    {
628 2
        if (is_array($value) || is_object($value)) {
629
            return true;
630
        }
631
632
        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 6
     * @return bool
641
     */
642 6
    public function isEmpty($value): bool
643 4
    {
644 2
        $value = is_object($value) && method_exists($value, 'toArray') ? $value->toArray() : $value;
645 6
        $value = is_object($value) ? (array) $value : $value;
646
647
        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 8
     * @return bool
656
     */
657 8
    public function doesntEmpty($value): bool
658 8
    {
659 8
        return ! $this->isEmpty($value);
660 8
    }
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 4
     * @param  int  $json_flags
670
     */
671 4
    public function store($array, string $path, bool $is_json = false, bool $sort_keys = false, int $json_flags = 0): void
672 4
    {
673 4
        $is_json
674 4
            ? $this->storeAsJson($path, $array, $sort_keys, $json_flags)
675
            : $this->storeAsArray($path, $array, $sort_keys);
676
    }
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 12
     */
686
    public function storeAsJson(string $path, $array, bool $sort_keys = false, int $flags = 0): void
687 12
    {
688
        $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 12
            return json_encode($array, $flags);
690 6
        }, $sort_keys);
691
    }
692
693 12
    /**
694 12
     * Save array to php file.
695
     *
696
     * @param  string  $path
697 12
     * @param  array|ArrayAccess  $array
698 12
     * @param  bool  $sort_keys
699
     */
700
    public function storeAsArray(string $path, $array, bool $sort_keys = false): void
701
    {
702
        $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
            return var_export($array, true);
704
        }, $sort_keys);
705
    }
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
    protected function prepareToStore(string $path, string $stub, array $array, callable $replace, bool $sort_keys = false): void
717
    {
718
        $array = (array) $array;
719
720
        if ($sort_keys) {
721
            $this->ksort($array);
722
        }
723
724
        $content = Stub::replace($stub, [
725
            '{{slot}}' => $replace($array),
726
        ]);
727
728
        File::store($path, $content);
729
    }
730
}
731