Passed
Push — main ( ff180e...a01d42 )
by Andrey
12:49 queued 11:21
created

Arr   F

Complexity

Total Complexity 85

Size/Duplication

Total Lines 641
Duplicated Lines 0 %

Test Coverage

Coverage 99.39%

Importance

Changes 9
Bugs 5 Features 0
Metric Value
eloc 127
dl 0
loc 641
ccs 162
cts 163
cp 0.9939
rs 2
c 9
b 5
f 0
wmc 85

34 Methods

Rating   Name   Duplication   Size   Complexity  
A renameKeysMap() 0 4 1
A set() 0 9 2
A filter() 0 9 3
A keys() 0 3 1
A sortByKeys() 0 5 1
A tap() 0 7 2
A addUnique() 0 11 3
A merge() 0 15 4
A store() 0 5 2
A get() 0 3 1
A only() 0 17 6
A isArrayable() 0 3 3
A map() 0 11 5
A wrap() 0 7 3
A storeAsJson() 0 5 1
A sort() 0 13 4
A flip() 0 3 1
A push() 0 7 2
A remove() 0 5 1
A longestStringLength() 0 5 2
A prepareToStore() 0 13 2
A storeAsArray() 0 5 1
A values() 0 3 1
A of() 0 3 1
A isEmpty() 0 6 5
A except() 0 9 3
A renameKeys() 0 11 2
A exists() 0 7 2
A doesntEmpty() 0 3 1
A flatten() 0 21 6
A unique() 0 3 1
A toArray() 0 17 6
A ksort() 0 13 4
A getKey() 0 3 2

How to fix   Complexity   

Complex Class

Complex classes like Arr often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Arr, and based on these observations, apply Extract Interface, too.

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

252
            /** @scrutinizer ignore-call */ 
253
            $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...
253
        }
254
255 26
        if (is_object($value)) {
256 16
            $value = method_exists($value, 'toArray') ? $value->toArray() : get_object_vars($value);
257
        }
258
259 26
        $array = $this->wrap($value);
260
261 26
        foreach ($array as &$item) {
262 26
            $item = $this->isArrayable($item) ? $this->toArray($item) : $item;
263
        }
264
265 26
        return $array;
266
    }
267
268
    /**
269
     * Determine if the given key exists in the provided array.
270
     *
271
     * @param  array|\ArrayAccess  $array
272
     * @param  mixed  $key
273
     *
274
     * @return bool
275
     */
276 34
    public function exists($array, $key): bool
277
    {
278 34
        if ($array instanceof ArrayAccess) {
279 2
            return $array->offsetExists($key);
280
        }
281
282 34
        return isset($array[$key]);
283
    }
284
285
    /**
286
     * Get an item from an array.
287
     *
288
     * @param  array|ArrayAccess  $array
289
     * @param  mixed  $key
290
     * @param  mixed|null  $default
291
     *
292
     * @return mixed|null
293
     */
294 34
    public function get($array, $key, $default = null)
295
    {
296 34
        return $array[$key] ?? $default;
297
    }
298
299
    /**
300
     * If the element key exists, then return the name of the key, otherwise the default value.
301
     *
302
     * @param  array|ArrayAccess  $array
303
     * @param  mixed  $key
304
     * @param  mixed  $default
305
     *
306
     * @return mixed|null
307
     */
308 32
    public function getKey($array, $key, $default = null)
309
    {
310 32
        return $this->exists($array, $key) ? $key : $default;
311
    }
312
313
    /**
314
     * Get all of the given array except for a specified array of keys.
315
     *
316
     * @param  array|ArrayAccess  $array
317
     * @param  array|callable|string  $keys
318
     *
319
     * @return array
320
     */
321 10
    public function except($array, $keys): array
322
    {
323 10
        $callback = is_callable($keys)
324 6
            ? $keys
325 4
            : static function ($key) use ($keys) {
326 4
                return empty($keys) || ! in_array($key, (array) $keys);
327 10
            };
328
329 10
        return $this->filter((array) $array, $callback, ARRAY_FILTER_USE_KEY);
330
    }
331
332
    /**
333
     * Get a subset of the items from the given array.
334
     *
335
     * @param  array|ArrayAccess  $array
336
     * @param  array|callable|string  $keys
337
     *
338
     * @return array
339
     */
340 8
    public function only($array, $keys): array
341
    {
342 8
        if (is_callable($keys)) {
343 4
            return $this->filter($array, $keys, ARRAY_FILTER_USE_KEY);
344
        }
345
346 4
        $result = [];
347
348 4
        foreach ((array) $keys as $index => $key) {
349 4
            if (is_array($key) && isset($array[$index])) {
350 4
                $result[$index] = $this->only($array[$index], $key);
351 4
            } elseif (isset($array[$key])) {
352 4
                $result[$key] = $array[$key];
353
            }
354
        }
355
356 4
        return $result;
357
    }
358
359
    /**
360
     * Iterates over each value in the <b>array</b> passing them to the <b>callback</b> function.
361
     * If the <b>callback</b> function returns true, the current value from <b>array</b> is returned into
362
     * the result array. Array keys are preserved.
363
     *
364
     * @see https://php.net/manual/en/function.array-filter.php
365
     *
366
     * @param  array|ArrayAccess  $array
367
     * @param  callable|null  $callback
368
     * @param  int  $mode
369
     *
370
     * @return array
371
     */
372 20
    public function filter($array, callable $callback = null, int $mode = 0): array
373
    {
374 20
        if (empty($callback)) {
375 2
            $callback = $mode === ARRAY_FILTER_USE_BOTH
376
                ? Empties::notEmptyBoth()
377 2
                : Empties::notEmpty();
378
        }
379
380 20
        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

380
        return array_filter(/** @scrutinizer ignore-type */ $array, $callback, $mode);
Loading history...
381
    }
382
383
    /**
384
     * Return all the keys or a subset of the keys of an array.
385
     *
386
     * @see https://php.net/manual/en/function.array-keys.php
387
     *
388
     * @param  mixed  $array
389
     *
390
     * @return array
391
     */
392 10
    public function keys($array): array
393
    {
394 10
        return array_keys($this->toArray($array));
395
    }
396
397
    /**
398
     * Return all the values of an array.
399
     *
400
     * @see  https://php.net/manual/en/function.array-values.php
401
     *
402
     * @param  mixed  $array
403
     *
404
     * @return array
405
     */
406 6
    public function values($array): array
407
    {
408 6
        return array_values($this->toArray($array));
409
    }
410
411
    /**
412
     * Exchanges all keys with their associated values in an array.
413
     *
414
     * @see  https://php.net/manual/en/function.array-flip.php
415
     *
416
     * @param  mixed  $array
417
     *
418
     * @return array
419
     */
420 10
    public function flip($array): array
421
    {
422 10
        return array_flip($this->toArray($array));
423
    }
424
425
    /**
426
     * Flatten a multi-dimensional array into a single level.
427
     *
428
     * @param  array  $array
429
     * @param  bool  $ignore_keys
430
     *
431
     * @return array
432
     */
433 10
    public function flatten(array $array, bool $ignore_keys = true): array
434
    {
435 10
        $result = [];
436
437 10
        foreach ($array as $key => $item) {
438 10
            if (! $this->isArrayable($item)) {
439 10
                $result = $ignore_keys
440 4
                    ? $this->push($result, $item)
441 10
                    : $this->set($result, $key, $item);
442
443 10
                continue;
444
            }
445
446 10
            $flatten = $this->flatten($item, $ignore_keys);
447
448 10
            $values = $ignore_keys ? array_values($flatten) : $flatten;
449
450 10
            $result = array_merge($result, $values);
451
        }
452
453 10
        return $ignore_keys ? array_values($result) : $result;
454
    }
455
456
    /**
457
     * Applies the callback to the elements of the given arrays.
458
     *
459
     * @param  array|ArrayAccess  $array
460
     * @param  callable  $callback
461
     * @param  bool  $recursive
462
     *
463
     * @return array
464
     */
465 10
    public function map($array, callable $callback, bool $recursive = false): array
466
    {
467 10
        foreach ($array as $key => &$value) {
468 10
            if ($recursive && is_array($value)) {
469 4
                $value = $this->map($value, $callback, $recursive);
470
            } else {
471 10
                $value = is_array($value) ? $value : $callback($value, $key);
472
            }
473
        }
474
475 10
        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...
476
    }
477
478
    /**
479
     * Push elements onto the end of array.
480
     *
481
     * @see  https://php.net/manual/en/function.array-push.php
482
     *
483
     * @param  array|ArrayAccess  $array
484
     * @param  mixed  ...$values
485
     *
486
     * @return array
487
     */
488 10
    public function push($array, ...$values): array
489
    {
490 10
        foreach ($values as $value) {
491 10
            array_push($array, $value);
492
        }
493
494 10
        return $array;
495
    }
496
497
    /**
498
     * Assigns a value to an array key.
499
     *
500
     * @param  array|ArrayAccess  $array
501
     * @param  mixed  $key
502
     * @param  mixed  $value
503
     *
504
     * @return array
505
     */
506 10
    public function set($array, $key, $value = null): array
507
    {
508 10
        if ($this->isArrayable($key)) {
509 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

509
            $array = $this->merge(/** @scrutinizer ignore-type */ $array, $key);
Loading history...
510
        } else {
511 10
            $array[$key] = $value;
512
        }
513
514 10
        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
     * Removes an array key.
519
     *
520
     * @param  array|ArrayAccess  $array
521
     * @param  mixed  $key
522
     *
523
     * @return array
524
     */
525 6
    public function remove($array, $key): array
526
    {
527 6
        unset($array[$key]);
528
529 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...
530
    }
531
532
    /**
533
     * Call the given Closure with the given value then return the value.
534
     *
535
     * @param  array|ArrayAccess  $array
536
     * @param  callable  $callback
537
     *
538
     * @return array
539
     */
540 4
    public function tap($array, callable $callback): array
541
    {
542 4
        foreach ($array as $key => &$value) {
543 4
            $callback($value, $key);
544
        }
545
546 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...
547
    }
548
549
    /**
550
     * Check if the item is an array.
551
     *
552
     * @param  mixed  $value
553
     *
554
     * @return bool
555
     */
556 44
    public function isArrayable($value = null): bool
557
    {
558 44
        return is_array($value) || is_object($value) || $value instanceof ArrayAccess;
559
    }
560
561
    /**
562
     * Determines if the array or arrayable object is empty.
563
     *
564
     * @param  mixed  $value
565
     *
566
     * @return bool
567
     */
568 8
    public function isEmpty($value): bool
569
    {
570 8
        $value = is_object($value) && method_exists($value, 'toArray') ? $value->toArray() : $value;
571 8
        $value = is_object($value) ? (array) $value : $value;
572
573 8
        return is_array($value) && empty($value);
574
    }
575
576
    /**
577
     * Determines if the value is doesn't empty.
578
     *
579
     * @param  mixed  $value
580
     *
581
     * @return bool
582
     */
583 2
    public function doesntEmpty($value): bool
584
    {
585 2
        return ! $this->isEmpty($value);
586
    }
587
588
    /**
589
     * Save array to php or json file.
590
     *
591
     * @param  array|ArrayAccess  $array
592
     * @param  string  $path
593
     * @param  bool  $is_json
594
     * @param  bool  $sort_keys
595
     * @param  int  $json_flags
596
     */
597 6
    public function store($array, string $path, bool $is_json = false, bool $sort_keys = false, int $json_flags = 0): void
598
    {
599 6
        $is_json
600 4
            ? $this->storeAsJson($path, $array, $sort_keys, $json_flags)
601 2
            : $this->storeAsArray($path, $array, $sort_keys);
602 6
    }
603
604
    /**
605
     * Save array to json file.
606
     *
607
     * @param  string  $path
608
     * @param  array|ArrayAccess  $array
609
     * @param  bool  $sort_keys
610
     * @param  int  $flags
611
     */
612 8
    public function storeAsJson(string $path, $array, bool $sort_keys = false, int $flags = 0): void
613
    {
614 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

614
        $this->prepareToStore($path, StubTool::JSON, /** @scrutinizer ignore-type */ $array, static function (array $array) use ($flags) {
Loading history...
615 8
            return json_encode($array, $flags);
616 8
        }, $sort_keys);
617 8
    }
618
619
    /**
620
     * Save array to php file.
621
     *
622
     * @param  string  $path
623
     * @param  array|ArrayAccess  $array
624
     * @param  bool  $sort_keys
625
     */
626 4
    public function storeAsArray(string $path, $array, bool $sort_keys = false): void
627
    {
628 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

628
        $this->prepareToStore($path, StubTool::PHP_ARRAY, /** @scrutinizer ignore-type */ $array, static function (array $array) {
Loading history...
629 4
            return var_export($array, true);
630 4
        }, $sort_keys);
631 4
    }
632
633
    /**
634
     * Prepare an array for writing to a file.
635
     *
636
     * @param  string  $path
637
     * @param  string  $stub
638
     * @param  array|ArrayAccess  $array
639
     * @param  callable  $replace
640
     * @param  bool  $sort_keys
641
     */
642 12
    protected function prepareToStore(string $path, string $stub, array $array, callable $replace, bool $sort_keys = false): void
643
    {
644 12
        $array = (array) $array;
645
646 12
        if ($sort_keys) {
647 6
            $this->ksort($array);
648
        }
649
650 12
        $content = Stub::replace($stub, [
651 12
            '{{slot}}' => $replace($array),
652
        ]);
653
654 12
        File::store($path, $content);
655 12
    }
656
}
657