Passed
Push — main ( a7b6ef...298d53 )
by Andrey
02:02 queued 12s
created

Arr::tap()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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

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

352
        return array_filter(/** @scrutinizer ignore-type */ $array, $callback, $mode);
Loading history...
353
    }
354
355
    /**
356
     * Return all the keys or a subset of the keys of an array.
357
     *
358
     * @see https://php.net/manual/en/function.array-keys.php
359
     *
360
     * @param  mixed  $array
361
     *
362
     * @return array
363
     */
364 10
    public function keys($array): array
365
    {
366 10
        return array_keys($this->toArray($array));
367
    }
368
369
    /**
370
     * Return all the values of an array.
371
     *
372
     * @see  https://php.net/manual/en/function.array-values.php
373
     *
374
     * @param  mixed  $array
375
     *
376
     * @return array
377
     */
378 6
    public function values($array): array
379
    {
380 6
        return array_values($this->toArray($array));
381
    }
382
383
    /**
384
     * Exchanges all keys with their associated values in an array.
385
     *
386
     * @see  https://php.net/manual/en/function.array-flip.php
387
     *
388
     * @param  mixed  $array
389
     *
390
     * @return array
391
     */
392 10
    public function flip($array): array
393
    {
394 10
        return array_flip($this->toArray($array));
395
    }
396
397
    /**
398
     * Flatten a multi-dimensional array into a single level.
399
     *
400
     * @param  array  $array
401
     * @param  bool  $ignore_keys
402
     *
403
     * @return array
404
     */
405 10
    public function flatten(array $array, bool $ignore_keys = true): array
406
    {
407 10
        $result = [];
408
409 10
        foreach ($array as $key => $item) {
410 10
            if (! $this->isArrayable($item)) {
411 10
                $result = $ignore_keys
412 4
                    ? $this->push($result, $item)
413 10
                    : $this->set($result, $key, $item);
414
415 10
                continue;
416
            }
417
418 10
            $flatten = $this->flatten($item, $ignore_keys);
419
420 10
            $values = $ignore_keys ? array_values($flatten) : $flatten;
421
422 10
            $result = array_merge($result, $values);
423
        }
424
425 10
        return $ignore_keys ? array_values($result) : $result;
426
    }
427
428
    /**
429
     * Applies the callback to the elements of the given arrays.
430
     *
431
     * @param  array|ArrayAccess  $array
432
     * @param  callable  $callback
433
     * @param  bool  $recursive
434
     *
435
     * @return array
436
     */
437 10
    public function map($array, callable $callback, bool $recursive = false): array
438
    {
439 10
        foreach ($array as $key => &$value) {
440 10
            if ($recursive && is_array($value)) {
441 4
                $value = $this->map($value, $callback, $recursive);
442
            } else {
443 10
                $value = is_array($value) ? $value : $callback($value, $key);
444
            }
445
        }
446
447 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...
448
    }
449
450
    /**
451
     * Push elements onto the end of array.
452
     *
453
     * @see  https://php.net/manual/en/function.array-push.php
454
     *
455
     * @param  array|ArrayAccess  $array
456
     * @param  mixed  ...$values
457
     *
458
     * @return array
459
     */
460 10
    public function push($array, ...$values): array
461
    {
462 10
        foreach ($values as $value) {
463 10
            array_push($array, $value);
464
        }
465
466 10
        return $array;
467
    }
468
469
    /**
470
     * Assigns a value to an array key.
471
     *
472
     * @param  array|ArrayAccess  $array
473
     * @param  mixed  $key
474
     * @param  mixed  $value
475
     *
476
     * @return array
477
     */
478 10
    public function set($array, $key, $value = null): array
479
    {
480 10
        if ($this->isArrayable($key)) {
481 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

481
            $array = $this->merge(/** @scrutinizer ignore-type */ $array, $key);
Loading history...
482
        } else {
483 10
            $array[$key] = $value;
484
        }
485
486 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...
487
    }
488
489
    /**
490
     * Removes an array key.
491
     *
492
     * @param  array|ArrayAccess  $array
493
     * @param  mixed  $key
494
     *
495
     * @return array
496
     */
497 6
    public function remove($array, $key): array
498
    {
499 6
        unset($array[$key]);
500
501 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...
502
    }
503
504
    /**
505
     * Call the given Closure with the given value then return the value.
506
     *
507
     * @param  array|ArrayAccess  $array
508
     * @param  callable  $callback
509
     *
510
     * @return array
511
     */
512 4
    public function tap($array, callable $callback): array
513
    {
514 4
        foreach ($array as $key => &$value) {
515 4
            $callback($value, $key);
516
        }
517
518 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...
519
    }
520
521
    /**
522
     * Check if the item is an array.
523
     *
524
     * @param  mixed  $value
525
     *
526
     * @return bool
527
     */
528 44
    public function isArrayable($value = null): bool
529
    {
530 44
        return is_array($value) || is_object($value) || $value instanceof ArrayAccess;
531
    }
532
533
    /**
534
     * Determines if the array or arrayable object is empty.
535
     *
536
     * @param  mixed  $value
537
     *
538
     * @return bool
539
     */
540 8
    public function isEmpty($value): bool
541
    {
542 8
        $value = is_object($value) && method_exists($value, 'toArray') ? $value->toArray() : $value;
543 8
        $value = is_object($value) ? (array) $value : $value;
544
545 8
        return is_array($value) && empty($value);
546
    }
547
548
    /**
549
     * Determines if the value is doesn't empty.
550
     *
551
     * @param  mixed  $value
552
     *
553
     * @return bool
554
     */
555 2
    public function doesntEmpty($value): bool
556
    {
557 2
        return ! $this->isEmpty($value);
558
    }
559
560
    /**
561
     * Save array to php or json file.
562
     *
563
     * @param  array|ArrayAccess  $array
564
     * @param  string  $path
565
     * @param  bool  $is_json
566
     * @param  bool  $sort_keys
567
     * @param  int  $json_flags
568
     */
569 6
    public function store($array, string $path, bool $is_json = false, bool $sort_keys = false, int $json_flags = 0): void
570
    {
571 6
        $is_json
572 4
            ? $this->storeAsJson($path, $array, $sort_keys, $json_flags)
573 2
            : $this->storeAsArray($path, $array, $sort_keys);
574 6
    }
575
576
    /**
577
     * Save array to json file.
578
     *
579
     * @param  string  $path
580
     * @param  array|ArrayAccess  $array
581
     * @param  bool  $sort_keys
582
     * @param  int  $flags
583
     */
584 8
    public function storeAsJson(string $path, $array, bool $sort_keys = false, int $flags = 0): void
585
    {
586 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

586
        $this->prepareToStore($path, StubTool::JSON, /** @scrutinizer ignore-type */ $array, static function (array $array) use ($flags) {
Loading history...
587 8
            return json_encode($array, $flags);
588 8
        }, $sort_keys);
589 8
    }
590
591
    /**
592
     * Save array to php file.
593
     *
594
     * @param  string  $path
595
     * @param  array|ArrayAccess  $array
596
     * @param  bool  $sort_keys
597
     */
598 4
    public function storeAsArray(string $path, $array, bool $sort_keys = false): void
599
    {
600 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

600
        $this->prepareToStore($path, StubTool::PHP_ARRAY, /** @scrutinizer ignore-type */ $array, static function (array $array) {
Loading history...
601 4
            return var_export($array, true);
602 4
        }, $sort_keys);
603 4
    }
604
605
    /**
606
     * Prepare an array for writing to a file.
607
     *
608
     * @param  string  $path
609
     * @param  string  $stub
610
     * @param  array|ArrayAccess  $array
611
     * @param  callable  $replace
612
     * @param  bool  $sort_keys
613
     */
614 12
    protected function prepareToStore(string $path, string $stub, array $array, callable $replace, bool $sort_keys = false): void
615
    {
616 12
        $array = (array) $array;
617
618 12
        if ($sort_keys) {
619 6
            $this->ksort($array);
620
        }
621
622 12
        $content = Stub::replace($stub, [
623 12
            '{{slot}}' => $replace($array),
624
        ]);
625
626 12
        File::store($path, $content);
627 12
    }
628
}
629