Passed
Pull Request — main (#22)
by Andrey
18:33 queued 03:32
created

Arr::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 4
rs 10
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
    public function renameKeys(array $array, callable $callback): array
23
    {
24
        $result = [];
25
26
        foreach ($array as $key => $value) {
27
            $new = $callback($key, $value);
28
29
            $result[$new] = $value;
30
        }
31
32
        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
    public function renameKeysMap(array $array, array $map): array
44
    {
45
        return $this->renameKeys($array, static function ($key) use ($map) {
46
            return $map[$key] ?? $key;
47
        });
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
    public function longestStringLength(array $array): int
58
    {
59
        return ! empty($array)
60
            ? max(array_map('mb_strlen', $array))
61
            : 0;
62
    }
63
64
    /**
65
     * Push one a unique element onto the end of array.
66
     *
67
     * @param  array  $array
68
     * @param  array|mixed  $values
69
     *
70
     * @return array
71
     */
72
    public function addUnique(array $array, $values): array
73
    {
74
        if ($this->isArrayable($values)) {
75
            foreach ($values as $value) {
76
                $array = $this->addUnique($array, $value);
77
            }
78
        } else {
79
            array_push($array, $values);
80
        }
81
82
        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
    public function sortByKeys(array $array, array $sorter): array
112
    {
113
        $sorter = array_intersect($sorter, array_keys($array));
114
        $array  = array_merge(array_flip($sorter), $array);
115
116
        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
    public function merge(...$arrays): array
128
    {
129
        $result = [];
130
131
        foreach ($arrays as $array) {
132
            foreach ($array as $key => $value) {
133
                if (is_array($value)) {
134
                    $value = $this->merge($result[$key] ?? [], $value);
135
                }
136
137
                $result[$key] = $value;
138
            }
139
        }
140
141
        return $result;
142
    }
143
144
    public function wrap($value = null): array
145
    {
146
        if (is_array($value)) {
147
            return $value;
148
        }
149
150
        return ! empty($value) ? [$value] : [];
151
    }
152
153
    public function toArray($value = null): array
154
    {
155
        if (is_object($value)) {
156
            $value = method_exists($value, 'toArray') ? $value->toArray() : get_object_vars($value);
157
        }
158
159
        $array = $this->wrap($value);
160
161
        foreach ($array as &$item) {
162
            $item = $this->isArrayable($item) ? $this->toArray($item) : $item;
163
        }
164
165
        return $array;
166
    }
167
168
    public function exists(array $array, $key): bool
169
    {
170
        return $array instanceof ArrayAccess
0 ignored issues
show
introduced by
$array is never a sub-type of ArrayAccess.
Loading history...
171
            ? $array->offsetExists($key)
172
            : isset($array[$key]);
173
    }
174
175
    public function get(array $array, $key, $default = null)
176
    {
177
        // TODO: $array[$key] ?? $default;
178
        return $this->exists($array, $key) ? $array[$key] : $default;
179
    }
180
181
    public function getKeyIfExist(array $array, $key, $default = null)
182
    {
183
        return isset($array[$key]) ? $key : $default;
184
    }
185
186
    public function except(array $array, $keys): array
187
    {
188
        $keys = (array) $keys;
189
190
        return array_filter($array, static function ($key) use ($keys) {
191
            return ! empty($keys) && ! in_array($key, $keys);
192
        }, ARRAY_FILTER_USE_KEY);
193
    }
194
195
    /**
196
     * Get a subset of the items from the given array.
197
     *
198
     * @param  array  $array
199
     * @param  array|string  $keys
200
     *
201
     * @return array
202
     */
203
    public function only(array $array, $keys): array
204
    {
205
        return array_intersect_key($array, array_flip((array) $keys));
206
    }
207
208
    public function map(array $array, callable $callback): array
209
    {
210
        return array_map($callback, $array);
211
    }
212
213
    public function isArrayable($value = null): bool
214
    {
215
        return is_array($value) || is_object($value) || $value instanceof ArrayAccess;
216
    }
217
218
    public function store(array $array, string $path, bool $is_json = false, bool $sort_keys = false): void
219
    {
220
        $is_json
221
            ? $this->storeAsJson($path, $array, $sort_keys)
222
            : $this->storeAsArray($path, $array, $sort_keys);
223
    }
224
225
    public function storeAsJson(string $path, array $array, bool $sort_keys = false): void
226
    {
227
        $this->prepareToStore($path, StubTool::JSON, $array, static function (array $array) {
228
            return json_encode($array);
229
        }, $sort_keys);
230
    }
231
232
    public function storeAsArray(string $path, array $array, bool $sort_keys = false): void
233
    {
234
        $this->prepareToStore($path, StubTool::PHP_ARRAY, $array, static function (array $array) {
235
            return var_export($array, true);
236
        }, $sort_keys);
237
    }
238
239
    protected function prepareToStore(string $path, string $stub, array $array, callable $replace, bool $sort_keys = false): void
240
    {
241
        if ($sort_keys) {
242
            ksort($array);
243
        }
244
245
        $content = Stub::replace($stub, [
246
            '{{slot}}' => $replace($array),
247
        ]);
248
249
        File::store($path, $content);
250
    }
251
}
252