Passed
Pull Request — main (#22)
by Andrey
26:45 queued 11:50
created

Arr::toArray()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
217
            return json_encode($array);
218
        }, $sort_keys);
219
    }
220
221
    public function storeAsArray(string $path, array $array, bool $sort_keys = false): void
222
    {
223
        $this->prepareToStore($path, Stub::CONFIG_FILE, $array, static function (array $array) {
224
            return var_export($array, true);
225
        }, $sort_keys);
226
    }
227
228
    protected function prepareToStore(string $path, string $stub, array $array, callable $replace, bool $sort_keys = false): void
229
    {
230
        if ($sort_keys) {
231
            ksort($array);
232
        }
233
234
        $content = Stub::replace($stub, [
235
            '{{slot}}' => $replace($array),
236
        ]);
237
238
        File::store($path, $content);
0 ignored issues
show
Bug Best Practice introduced by
The method Helldar\Support\Helpers\Filesystem\File::store() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

238
        File::/** @scrutinizer ignore-call */ 
239
              store($path, $content);
Loading history...
239
    }
240
}
241