Passed
Push — main ( 938ee5...089f55 )
by Andrey
12:50 queued 10:28
created

Arr::get()   B

Complexity

Conditions 8
Paths 7

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 14
c 1
b 0
f 0
nc 7
nop 3
dl 0
loc 27
ccs 14
cts 14
cp 1
crap 8
rs 8.4444
1
<?php
2
/******************************************************************************
3
 * This file is part of the "andrey-helldar/support" project.                 *
4
 *                                                                            *
5
 * @author Andrey Helldar <[email protected]>                                *
6
 *                                                                            *
7
 * @copyright 2021 Andrey Helldar                                             *
8
 *                                                                            *
9
 * @license MIT                                                               *
10
 *                                                                            *
11
 * @see https://github.com/andrey-helldar/support                             *
12
 *                                                                            *
13
 * For the full copyright and license information, please view the LICENSE    *
14
 * file that was distributed with this source code.                           *
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
        return array_key_exists($key, $array);
296
    }
297
298
    /**
299
     * Get an item from an array.
300
     *
301
     * @see https://github.com/illuminate/collections/blob/master/Arr.php
302
     *
303
     * @param  array|ArrayAccess  $array
304
     * @param  mixed  $key
305
     * @param  mixed|null  $default
306
     *
307
     * @return mixed|null
308
     */
309 207
    public function get($array, $key, $default = null)
310
    {
311 207
        if (! $this->isArrayable($array)) {
312 2
            return $default;
313
        }
314
315 207
        if (is_null($key)) {
316 2
            return $array;
317
        }
318
319 207
        if ($this->exists($array, $key)) {
320 191
            return $array[$key];
321
        }
322
323 183
        if (strpos($key, '.') === false) {
324 183
            return $array[$key] ?? $default;
325
        }
326
327 2
        foreach (explode('.', $key) as $segment) {
328 2
            if ($this->isArrayable($array) && $this->exists($array, $segment)) {
329 2
                $array = $array[$segment];
330
            } else {
331 2
                return $default;
332
            }
333
        }
334
335 2
        return $array;
336
    }
337
338
    /**
339
     * If the element key exists, then return the name of the key, otherwise the default value.
340
     *
341
     * @param  array|ArrayAccess  $array
342
     * @param  mixed  $key
343
     * @param  mixed  $default
344
     *
345
     * @return mixed|null
346
     */
347 2
    public function getKey($array, $key, $default = null)
348
    {
349 2
        return $this->exists($array, $key) ? $key : $default;
350
    }
351
352
    /**
353
     * Get all of the given array except for a specified array of keys.
354
     *
355
     * @param  array|ArrayAccess  $array
356
     * @param  array|callable|string  $keys
357
     *
358
     * @return array
359
     */
360 10
    public function except($array, $keys): array
361
    {
362 10
        $callback = is_callable($keys)
363 6
            ? $keys
364 4
            : static function ($key) use ($keys) {
365 4
                return empty($keys) || ! in_array($key, (array) $keys);
366 10
            };
367
368 10
        return $this->filter((array) $array, $callback, ARRAY_FILTER_USE_KEY);
369
    }
370
371
    /**
372
     * Get a subset of the items from the given array.
373
     *
374
     * @param  array|ArrayAccess  $array
375
     * @param  array|callable|string  $keys
376
     *
377
     * @return array
378
     */
379 158
    public function only($array, $keys): array
380
    {
381 158
        if (is_callable($keys)) {
382 4
            return $this->filter($array, $keys, ARRAY_FILTER_USE_KEY);
383
        }
384
385 154
        $result = [];
386
387 154
        foreach ((array) $keys as $index => $key) {
388 154
            if (is_array($key) && isset($array[$index])) {
389 4
                $result[$index] = $this->only($array[$index], $key);
390 154
            } elseif (isset($array[$key])) {
391 152
                $result[$key] = $array[$key];
392
            }
393
        }
394
395 154
        return $result;
396
    }
397
398
    /**
399
     * Iterates over each value in the <b>array</b> passing them to the <b>callback</b> function.
400
     * If the <b>callback</b> function returns true, the current value from <b>array</b> is returned into
401
     * the result array. Array keys are preserved.
402
     *
403
     * @see https://php.net/manual/en/function.array-filter.php
404
     *
405
     * @param  array|ArrayAccess  $array
406
     * @param  callable|null  $callback
407
     * @param  int  $mode
408
     *
409
     * @return array
410
     */
411 41
    public function filter($array, callable $callback = null, int $mode = 0): array
412
    {
413 41
        if (empty($callback)) {
414 23
            $callback = $mode === ARRAY_FILTER_USE_BOTH
415
                ? Empties::notEmptyBoth()
416 23
                : Empties::notEmpty();
417
        }
418
419 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

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

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

657
        $this->prepareToStore($path, StubTool::JSON, /** @scrutinizer ignore-type */ $array, static function (array $array) use ($flags) {
Loading history...
658 8
            return json_encode($array, $flags);
659 8
        }, $sort_keys);
660 8
    }
661
662
    /**
663
     * Save array to php file.
664
     *
665
     * @param  string  $path
666
     * @param  array|ArrayAccess  $array
667
     * @param  bool  $sort_keys
668
     */
669 4
    public function storeAsArray(string $path, $array, bool $sort_keys = false): void
670
    {
671 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

671
        $this->prepareToStore($path, StubTool::PHP_ARRAY, /** @scrutinizer ignore-type */ $array, static function (array $array) {
Loading history...
672 4
            return var_export($array, true);
673 4
        }, $sort_keys);
674 4
    }
675
676
    /**
677
     * Prepare an array for writing to a file.
678
     *
679
     * @param  string  $path
680
     * @param  string  $stub
681
     * @param  array|ArrayAccess  $array
682
     * @param  callable  $replace
683
     * @param  bool  $sort_keys
684
     */
685 12
    protected function prepareToStore(string $path, string $stub, array $array, callable $replace, bool $sort_keys = false): void
686
    {
687 12
        $array = (array) $array;
688
689 12
        if ($sort_keys) {
690 6
            $this->ksort($array);
691
        }
692
693 12
        $content = Stub::replace($stub, [
694 12
            '{{slot}}' => $replace($array),
695
        ]);
696
697 12
        File::store($path, $content);
698 12
    }
699
}
700