Passed
Push — main ( 298d53...8aefd5 )
by Andrey
12:51 queued 11:03
created

Arr::unique()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
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 $this->unique($array);
98
    }
99
100
    /**
101
     * Removes duplicate values from an array.
102
     *
103
     * Sorting type flags:
104
     *   SORT_REGULAR       - compare items normally
105
     *   SORT_NUMERIC       - compare items numerically
106
     *   SORT_STRING        - compare items as strings
107
     *   SORT_LOCALE_STRING - compare items as strings, based on the current locale
108
     *
109
     * @see https://php.net/manual/en/function.array-unique.php
110
     *
111
     * @param  array  $array
112
     * @param  int  $flags
113
     *
114
     * @return array
115
     */
116 10
    public function unique(array $array, int $flags = SORT_STRING): array
117
    {
118 10
        return array_unique($array, $flags);
119
    }
120
121
    /**
122
     * Sort an associative array in the order specified by an array of keys.
123
     *
124
     * Example:
125
     *
126
     *  $arr = ['q' => 1, 'r' => 2, 's' => 5, 'w' => 123];
127
     *
128
     *  Arr::sortByKeys($arr, ['q', 'w', 'e']);
129
     *
130
     * print_r($arr);
131
     *
132
     *   Array
133
     *   (
134
     *     [q] => 1
135
     *     [w] => 123
136
     *     [r] => 2
137
     *     [s] => 5
138
     *   )
139
     *
140
     * @see https://gist.github.com/Ellrion/a3145621f936aa9416f4c04987533d8d#file-helper-php
141
     *
142
     * @param  array  $array
143
     * @param  array  $sorter
144
     *
145
     * @return array
146
     */
147 4
    public function sortByKeys(array $array, array $sorter): array
148
    {
149 4
        $sorter = array_intersect($sorter, array_keys($array));
150
151 4
        return array_merge(array_flip($sorter), $array);
152
    }
153
154
    /**
155
     * Recursively sorting an array by values.
156
     *
157
     * @param  array  $array
158
     * @param  callable|null  $callback
159
     *
160
     * @return array
161
     */
162 10
    public function sort(array $array, callable $callback = null): array
163
    {
164 10
        $callback = $callback ?: Sorter::defaultCallback();
165
166 10
        usort($array, $callback);
167
168 10
        foreach ($array as &$value) {
169 10
            if (is_array($value)) {
170 8
                $value = $this->sort($value, $callback);
171
            }
172
        }
173
174 10
        return $array;
175
    }
176
177
    /**
178
     * Recursively sorting an array by keys.
179
     *
180
     * @param  array  $array
181
     * @param  callable|null  $callback
182
     *
183
     * @return array
184
     */
185 16
    public function ksort(array $array, callable $callback = null): array
186
    {
187 16
        $callback = $callback ?: Sorter::defaultCallback();
188
189 16
        uksort($array, $callback);
190
191 16
        foreach ($array as &$value) {
192 16
            if (is_array($value)) {
193 10
                $value = $this->ksort($value, $callback);
194
            }
195
        }
196
197 16
        return $array;
198
    }
199
200
    /**
201
     * Merge one or more arrays recursively.
202
     * Don't forget that numeric keys NOT will be renumbered!
203
     *
204
     * @param  array[]  ...$arrays
205
     *
206
     * @return array
207
     */
208 10
    public function merge(...$arrays): array
209
    {
210 10
        $result = [];
211
212 10
        foreach ($arrays as $array) {
213 10
            foreach ($array as $key => $value) {
214 10
                if (is_array($value)) {
215 6
                    $value = $this->merge($result[$key] ?? [], $value);
216
                }
217
218 10
                $result[$key] = $value;
219
            }
220
        }
221
222 10
        return $result;
223
    }
224
225
    /**
226
     * If the given value is not an array and not null, wrap it in one.
227
     *
228
     * @param  mixed  $value
229
     *
230
     * @return array
231
     */
232 88
    public function wrap($value = null): array
233
    {
234 88
        if (is_array($value)) {
235 40
            return $value;
236
        }
237
238 72
        return ! empty($value) ? [$value] : [];
239
    }
240
241
    /**
242
     * Get the instance as an array.
243
     *
244
     * @param  mixed  $value
245
     *
246
     * @return array
247
     */
248 26
    public function toArray($value = null): array
249
    {
250 26
        if (InstanceHelper::of($value, ArrayableHelper::class)) {
251 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

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

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

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

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

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