Passed
Pull Request — main (#87)
by Andrey
13:24
created

Arr   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 402
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 9
Bugs 2 Features 0
Metric Value
eloc 82
c 9
b 2
f 0
dl 0
loc 402
ccs 104
cts 104
cp 1
rs 6
wmc 55

22 Methods

Rating   Name   Duplication   Size   Complexity  
A sortByKeys() 0 6 1
A addUnique() 0 11 3
A merge() 0 17 4
A get() 0 3 1
A wrap() 0 7 3
A longestStringLength() 0 5 2
A renameKeys() 0 11 2
A exists() 0 7 2
A renameKeysMap() 0 4 1
A toArray() 0 13 5
A getKey() 0 3 2
A except() 0 9 3
A store() 0 5 2
A only() 0 17 6
A map() 0 7 2
A isArrayable() 0 3 3
A storeAsJson() 0 5 1
A prepareToStore() 0 13 2
A storeAsArray() 0 5 1
A isEmpty() 0 6 5
A doesntEmpty() 0 3 1
A sort() 0 7 3

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

259
            return array_filter(/** @scrutinizer ignore-type */ $array, $keys, ARRAY_FILTER_USE_KEY);
Loading history...
260
        }
261
262 2
        $result = [];
263
264 2
        foreach ((array) $keys as $index => $key) {
265 2
            if (is_array($key) && isset($array[$index])) {
266 2
                $result[$index] = $this->only($array[$index], $key);
267 2
            } elseif (isset($array[$key])) {
268 2
                $result[$key] = $array[$key];
269
            }
270
        }
271
272 2
        return $result;
273
    }
274
275
    /**
276
     * Applies the callback to the elements of the given arrays.
277
     *
278
     * @param  array|ArrayAccess  $array
279
     * @param  callable  $callback
280
     *
281
     * @return array
282
     */
283 2
    public function map($array, callable $callback): array
284
    {
285 2
        foreach ($array as $key => &$value) {
286 2
            $value = $callback($value, $key);
287
        }
288
289 2
        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...
290
    }
291
292
    /**
293
     * Check if the item is an array.
294
     *
295
     * @param  mixed  $value
296
     *
297
     * @return bool
298
     */
299 6
    public function isArrayable($value = null): bool
300
    {
301 6
        return is_array($value) || is_object($value) || $value instanceof ArrayAccess;
302
    }
303
304
    /**
305
     * Determines if the array or arrayable object is empty.
306
     *
307
     * @param  mixed  $value
308
     *
309
     * @return bool
310
     */
311 8
    public function isEmpty($value): bool
312
    {
313 8
        $value = is_object($value) && method_exists($value, 'toArray') ? $value->toArray() : $value;
314 8
        $value = is_object($value) ? (array) $value : $value;
315
316 8
        return is_array($value) && empty($value);
317
    }
318
319
    /**
320
     * Determines if the value is doesn't empty.
321
     *
322
     * @param  mixed  $value
323
     *
324
     * @return bool
325
     */
326 2
    public function doesntEmpty($value): bool
327
    {
328 2
        return ! $this->isEmpty($value);
329
    }
330
331
    /**
332
     * Save array to php or json file.
333
     *
334
     * @param  array|ArrayAccess  $array
335
     * @param  string  $path
336
     * @param  bool  $is_json
337
     * @param  bool  $sort_keys
338
     * @param  int  $json_flags
339
     */
340 6
    public function store($array, string $path, bool $is_json = false, bool $sort_keys = false, int $json_flags = 0): void
341
    {
342 6
        $is_json
343 4
            ? $this->storeAsJson($path, $array, $sort_keys, $json_flags)
344 2
            : $this->storeAsArray($path, $array, $sort_keys);
345 6
    }
346
347
    /**
348
     * Save array to json file.
349
     *
350
     * @param  string  $path
351
     * @param  array|ArrayAccess  $array
352
     * @param  bool  $sort_keys
353
     * @param  int  $flags
354
     */
355 8
    public function storeAsJson(string $path, $array, bool $sort_keys = false, int $flags = 0): void
356
    {
357 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

357
        $this->prepareToStore($path, StubTool::JSON, /** @scrutinizer ignore-type */ $array, static function (array $array) use ($flags) {
Loading history...
358 8
            return json_encode($array, $flags);
359 8
        }, $sort_keys);
360 8
    }
361
362
    /**
363
     * Save array to php file.
364
     *
365
     * @param  string  $path
366
     * @param  array|ArrayAccess  $array
367
     * @param  bool  $sort_keys
368
     */
369 4
    public function storeAsArray(string $path, $array, bool $sort_keys = false): void
370
    {
371 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

371
        $this->prepareToStore($path, StubTool::PHP_ARRAY, /** @scrutinizer ignore-type */ $array, static function (array $array) {
Loading history...
372 4
            return var_export($array, true);
373 4
        }, $sort_keys);
374 4
    }
375
376
    /**
377
     * Prepare an array for writing to a file.
378
     *
379
     * @param  string  $path
380
     * @param  string  $stub
381
     * @param  array|ArrayAccess  $array
382
     * @param  callable  $replace
383
     * @param  bool  $sort_keys
384
     */
385 12
    protected function prepareToStore(string $path, string $stub, array $array, callable $replace, bool $sort_keys = false): void
386
    {
387 12
        $array = (array) $array;
388
389 12
        if ($sort_keys) {
390 6
            $this->sort($array);
391
        }
392
393 12
        $content = Stub::replace($stub, [
394 12
            '{{slot}}' => $replace($array),
395
        ]);
396
397 12
        File::store($path, $content);
398 12
    }
399
400
    /**
401
     * Recursively sorting an array by keys.
402
     *
403
     * @param  array  $array
404
     */
405
    protected function sort(array &$array): void
406
    {
407
        ksort($array, SORT_FLAG_CASE ^ SORT_STRING);
408
409
        foreach ($array as $key => &$value) {
410
            if (is_array($value)) {
411
                $this->sort($value);
412
            }
413
        }
414
    }
415
}
416