Passed
Pull Request — main (#113)
by Andrey
15:18
created

Arr::values()   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
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
crap 1
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\Tools\Sorter;
8
use Helldar\Support\Facades\Tools\Stub;
9
use Helldar\Support\Tools\Stub as StubTool;
10
11
class Arr
12
{
13
    /**
14
     * Get a new arrayable object from the given array.
15
     *
16
     * @param  array|ArrayAccess|string|null  $value
17
     *
18
     * @return \Helldar\Support\Helpers\Ables\Arrayable
19
     */
20
    public function of($value = []): Ables\Arrayable
21
    {
22
        return new Ables\Arrayable($value);
23 4
    }
24
25 4
    /**
26
     * Renaming array keys.
27 4
     * As the second parameter, a callback function is passed, which determines the actions for processing the value.
28 4
     * The output of the function must be a string with a name.
29
     *
30 4
     * @param  array  $array
31
     * @param  callable  $callback
32
     *
33 4
     * @return array
34
     */
35
    public function renameKeys(array $array, callable $callback): array
36
    {
37
        $result = [];
38
39
        foreach ($array as $key => $value) {
40
            $new = $callback($key, $value);
41
42
            $result[$new] = $value;
43
        }
44 2
45
        return $result;
46 2
    }
47 2
48 2
    /**
49
     * Renaming array keys with map.
50
     *
51
     * @param  array  $array
52
     * @param  array  $map
53
     *
54
     * @return array
55
     */
56
    public function renameKeysMap(array $array, array $map): array
57
    {
58 2
        return $this->renameKeys($array, static function ($key) use ($map) {
59
            return $map[$key] ?? $key;
60 2
        });
61 2
    }
62 2
63
    /**
64
     * Get the size of the longest text element of the array.
65
     *
66
     * @param  array  $array
67
     *
68
     * @return int
69
     */
70
    public function longestStringLength(array $array): int
71
    {
72
        return ! empty($array)
73 2
            ? max(array_map('mb_strlen', $array))
74
            : 0;
75 2
    }
76 2
77 2
    /**
78
     * Push one a unique element onto the end of array.
79
     *
80 2
     * @param  array  $array
81
     * @param  mixed  $values
82
     *
83 2
     * @return array
84
     */
85
    public function addUnique(array $array, $values): array
86
    {
87
        if ($this->isArrayable($values)) {
88
            foreach ($values as $value) {
89
                $array = $this->addUnique($array, $value);
90
            }
91
        } else {
92
            array_push($array, $values);
93
        }
94
95
        return array_unique($array);
96
    }
97
98
    /**
99
     * Sort an associative array in the order specified by an array of keys.
100
     *
101
     * Example:
102
     *
103
     *  $arr = ['q' => 1, 'r' => 2, 's' => 5, 'w' => 123];
104
     *
105
     *  Arr::sortByKeys($arr, ['q', 'w', 'e']);
106
     *
107
     * print_r($arr);
108
     *
109
     *   Array
110
     *   (
111
     *     [q] => 1
112 2
     *     [w] => 123
113
     *     [r] => 2
114 2
     *     [s] => 5
115 2
     *   )
116
     *
117 2
     * @see https://gist.github.com/Ellrion/a3145621f936aa9416f4c04987533d8d#file-helper-php
118
     *
119
     * @param  array  $array
120
     * @param  array  $sorter
121
     *
122
     * @return array
123
     */
124
    public function sortByKeys(array $array, array $sorter): array
125
    {
126
        $sorter = array_intersect($sorter, array_keys($array));
127
        $array  = array_merge(array_flip($sorter), $array);
128 4
129
        return $array;
130 4
    }
131
132 4
    /**
133
     * Recursively sorting an array by values.
134 4
     *
135 4
     * @param  array  $array
136 4
     * @param  callable|null  $callback
137
     *
138
     * @return array
139
     */
140 4
    public function sort(array $array, callable $callback = null): array
141
    {
142
        $callback = $callback ?: Sorter::defaultCallback();
143
144
        usort($array, $callback);
145
146
        foreach ($array as &$value) {
147
            if (is_array($value)) {
148
                $value = $this->sort($value, $callback);
149
            }
150
        }
151 12
152
        return $array;
153 12
    }
154
155 12
    /**
156
     * Recursively sorting an array by keys.
157 12
     *
158 12
     * @param  array  $array
159 6
     * @param  callable|null  $callback
160
     *
161
     * @return array
162
     */
163 12
    public function ksort(array $array, callable $callback = null): array
164
    {
165
        $callback = $callback ?: Sorter::defaultCallback();
166
167
        uksort($array, $callback);
168
169
        foreach ($array as $key => &$value) {
170
            if (is_array($value)) {
171
                $value = $this->ksort($value, $callback);
172
            }
173
        }
174 2
175
        return $array;
176 2
    }
177
178 2
    /**
179 2
     * Merge one or more arrays recursively.
180 2
     * Don't forget that numeric keys NOT will be renumbered!
181 2
     *
182
     * @param  array[]  ...$arrays
183
     *
184 2
     * @return array
185
     */
186
    public function merge(...$arrays): array
187
    {
188 2
        $result = [];
189
190
        foreach ($arrays as $array) {
191
            foreach ($array as $key => $value) {
192
                if (is_array($value)) {
193
                    $value = $this->merge($result[$key] ?? [], $value);
194
                }
195
196
                $result[$key] = $value;
197
            }
198 64
        }
199
200 64
        return $this->ksort($result);
201 16
    }
202
203
    /**
204 58
     * If the given value is not an array and not null, wrap it in one.
205
     *
206
     * @param  mixed  $value
207
     *
208
     * @return array
209
     */
210
    public function wrap($value = null): array
211
    {
212
        if (is_array($value)) {
213
            return $value;
214 2
        }
215
216 2
        return ! empty($value) ? [$value] : [];
217 2
    }
218
219
    /**
220 2
     * Get the instance as an array.
221
     *
222 2
     * @param  mixed  $value
223 2
     *
224
     * @return array
225
     */
226 2
    public function toArray($value = null): array
227
    {
228
        if (is_object($value)) {
229
            $value = method_exists($value, 'toArray') ? $value->toArray() : get_object_vars($value);
230
        }
231
232
        $array = $this->wrap($value);
233
234
        foreach ($array as &$item) {
235
            $item = $this->isArrayable($item) ? $this->toArray($item) : $item;
236
        }
237 34
238
        return $array;
239 34
    }
240 2
241
    /**
242
     * Determine if the given key exists in the provided array.
243 34
     *
244
     * @param  array|\ArrayAccess  $array
245
     * @param  mixed  $key
246
     *
247
     * @return bool
248
     */
249
    public function exists($array, $key): bool
250
    {
251
        if ($array instanceof ArrayAccess) {
252
            return $array->offsetExists($key);
253
        }
254
255 34
        return isset($array[$key]);
256
    }
257 34
258
    /**
259
     * Get an item from an array.
260
     *
261
     * @param  array|ArrayAccess  $array
262
     * @param  mixed  $key
263
     * @param  mixed|null  $default
264
     *
265
     * @return mixed|null
266
     */
267
    public function get($array, $key, $default = null)
268
    {
269 32
        return $array[$key] ?? $default;
270
    }
271 32
272
    /**
273
     * If the element key exists, then return the name of the key, otherwise the default value.
274
     *
275
     * @param  array|ArrayAccess  $array
276
     * @param  mixed  $key
277
     * @param  mixed  $default
278
     *
279
     * @return mixed|null
280
     */
281
    public function getKey($array, $key, $default = null)
282 4
    {
283
        return $this->exists($array, $key) ? $key : $default;
284 4
    }
285 2
286 2
    /**
287 2
     * Get all of the given array except for a specified array of keys.
288 4
     *
289
     * @param  array|ArrayAccess  $array
290 4
     * @param  array|callable|string  $keys
291
     *
292
     * @return array
293
     */
294
    public function except($array, $keys): array
295
    {
296
        $callback = is_callable($keys)
297
            ? $keys
298
            : static function ($key) use ($keys) {
299
                return empty($keys) || ! in_array($key, (array) $keys);
300
            };
301 4
302
        return $this->filter((array) $array, $callback, ARRAY_FILTER_USE_KEY);
303 4
    }
304 2
305
    /**
306
     * Get a subset of the items from the given array.
307 2
     *
308
     * @param  array|ArrayAccess  $array
309 2
     * @param  array|callable|string  $keys
310 2
     *
311 2
     * @return array
312 2
     */
313 2
    public function only($array, $keys): array
314
    {
315
        if (is_callable($keys)) {
316
            return $this->filter($array, $keys, ARRAY_FILTER_USE_KEY);
317 2
        }
318
319
        $result = [];
320
321
        foreach ((array) $keys as $index => $key) {
322
            if (is_array($key) && isset($array[$index])) {
323
                $result[$index] = $this->only($array[$index], $key);
324
            } elseif (isset($array[$key])) {
325
                $result[$key] = $array[$key];
326
            }
327 2
        }
328
329 2
        return $result;
330
    }
331 2
332 2
    /**
333 2
     * Iterates over each value in the <b>array</b> passing them to the <b>callback</b> function.
334
     * If the <b>callback</b> function returns true, the current value from <b>array</b> is returned into
335 2
     * the result array. Array keys are preserved.
336
     *
337
     * @see https://php.net/manual/en/function.array-filter.php
338 2
     *
339
     * @param  array|ArrayAccess  $array
340 2
     * @param  callable  $callback
341
     * @param  int  $mode
342
     *
343 2
     * @return array
344
     */
345
    public function filter($array, callable $callback, int $mode = 0): array
346
    {
347
        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

347
        return array_filter(/** @scrutinizer ignore-type */ $array, $callback, $mode);
Loading history...
348
    }
349
350
    /**
351
     * Return all the values of an array.
352
     *
353
     * @see  https://php.net/manual/en/function.array-values.php
354
     *
355 4
     * @param  mixed  $array
356
     *
357 4
     * @return array
358 4
     */
359 2
    public function values($array): array
360
    {
361 4
        return array_values($this->toArray($array));
362
    }
363
364
    /**
365 4
     * Flatten a multi-dimensional array into a single level.
366
     *
367
     * @param  array  $array
368
     * @param  bool  $ignore_keys
369
     *
370
     * @return array
371
     */
372
    public function flatten(array $array, bool $ignore_keys = true): array
373
    {
374
        $result = [];
375 8
376
        foreach ($array as $key => $item) {
377 8
            if (! $this->isArrayable($item)) {
378
                $ignore_keys
379
                    ? $result[]     = $item
380
                    : $result[$key] = $item;
381
382
                continue;
383
            }
384
385
            $flatten = $this->flatten($item, $ignore_keys);
386
387 8
            $values = $ignore_keys ? array_values($flatten) : $flatten;
388
389 8
            $result = array_merge($result, $values);
390 8
        }
391
392 8
        return $ignore_keys ? array_values($result) : $result;
393
    }
394
395
    /**
396
     * Applies the callback to the elements of the given arrays.
397
     *
398
     * @param  array|ArrayAccess  $array
399
     * @param  callable  $callback
400
     * @param  bool  $recursive
401
     *
402 2
     * @return array
403
     */
404 2
    public function map($array, callable $callback, bool $recursive = false): array
405
    {
406
        foreach ($array as $key => &$value) {
407
            if ($recursive && is_array($value)) {
408
                $value = $this->map($value, $callback, $recursive);
409
            } else {
410
                $value = is_array($value) ? $value : $callback($value, $key);
411
            }
412
        }
413
414
        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...
415
    }
416 6
417
    /**
418 6
     * Check if the item is an array.
419 4
     *
420 2
     * @param  mixed  $value
421 6
     *
422
     * @return bool
423
     */
424
    public function isArrayable($value = null): bool
425
    {
426
        return is_array($value) || is_object($value) || $value instanceof ArrayAccess;
427
    }
428
429
    /**
430
     * Determines if the array or arrayable object is empty.
431 8
     *
432
     * @param  mixed  $value
433 8
     *
434 8
     * @return bool
435 8
     */
436 8
    public function isEmpty($value): bool
437
    {
438
        $value = is_object($value) && method_exists($value, 'toArray') ? $value->toArray() : $value;
439
        $value = is_object($value) ? (array) $value : $value;
440
441
        return is_array($value) && empty($value);
442
    }
443
444
    /**
445 4
     * Determines if the value is doesn't empty.
446
     *
447 4
     * @param  mixed  $value
448 4
     *
449 4
     * @return bool
450 4
     */
451
    public function doesntEmpty($value): bool
452
    {
453
        return ! $this->isEmpty($value);
454
    }
455
456
    /**
457
     * Save array to php or json file.
458
     *
459
     * @param  array|ArrayAccess  $array
460
     * @param  string  $path
461 12
     * @param  bool  $is_json
462
     * @param  bool  $sort_keys
463 12
     * @param  int  $json_flags
464
     */
465 12
    public function store($array, string $path, bool $is_json = false, bool $sort_keys = false, int $json_flags = 0): void
466 6
    {
467
        $is_json
468
            ? $this->storeAsJson($path, $array, $sort_keys, $json_flags)
469 12
            : $this->storeAsArray($path, $array, $sort_keys);
470 12
    }
471
472
    /**
473 12
     * Save array to json file.
474 12
     *
475
     * @param  string  $path
476
     * @param  array|ArrayAccess  $array
477
     * @param  bool  $sort_keys
478
     * @param  int  $flags
479
     */
480
    public function storeAsJson(string $path, $array, bool $sort_keys = false, int $flags = 0): void
481
    {
482
        $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

482
        $this->prepareToStore($path, StubTool::JSON, /** @scrutinizer ignore-type */ $array, static function (array $array) use ($flags) {
Loading history...
483
            return json_encode($array, $flags);
484
        }, $sort_keys);
485
    }
486
487
    /**
488
     * Save array to php file.
489
     *
490
     * @param  string  $path
491
     * @param  array|ArrayAccess  $array
492
     * @param  bool  $sort_keys
493
     */
494
    public function storeAsArray(string $path, $array, bool $sort_keys = false): void
495
    {
496
        $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

496
        $this->prepareToStore($path, StubTool::PHP_ARRAY, /** @scrutinizer ignore-type */ $array, static function (array $array) {
Loading history...
497
            return var_export($array, true);
498
        }, $sort_keys);
499
    }
500
501
    /**
502
     * Prepare an array for writing to a file.
503
     *
504
     * @param  string  $path
505
     * @param  string  $stub
506
     * @param  array|ArrayAccess  $array
507
     * @param  callable  $replace
508
     * @param  bool  $sort_keys
509
     */
510
    protected function prepareToStore(string $path, string $stub, array $array, callable $replace, bool $sort_keys = false): void
511
    {
512
        $array = (array) $array;
513
514
        if ($sort_keys) {
515
            $this->ksort($array);
516
        }
517
518
        $content = Stub::replace($stub, [
519
            '{{slot}}' => $replace($array),
520
        ]);
521
522
        File::store($path, $content);
523
    }
524
}
525