Passed
Push — master ( b318ac...f0530b )
by Paul
07:00 queued 20s
created

Arr::searchByKey()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.3731

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 10
ccs 5
cts 7
cp 0.7143
rs 10
cc 4
nc 3
nop 3
crap 4.3731
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Helpers;
4
5
use GeminiLabs\SiteReviews\Arguments;
6
use GeminiLabs\SiteReviews\Helper;
7
use GeminiLabs\SiteReviews\Helpers\Cast;
8
9
class Arr
10
{
11
    /**
12
     * @return bool
13
     */
14 8
    public static function compare(array $arr1, array $arr2)
15
    {
16 8
        sort($arr1);
17 8
        sort($arr2);
18 8
        return $arr1 == $arr2;
19
    }
20
21
    /**
22
     * Returns an empty array if value is scalar
23
     * @param mixed $value
24
     * @return array
25
     */
26 46
    public static function consolidate($value)
27
    {
28 46
        if ($value instanceof Arguments) {
29 6
            return $value->toArray();
30
        }
31 46
        if (is_object($value)) {
32 18
            $values = get_object_vars($value);
33 18
            $value = Helper::ifEmpty($values, (array) $value, $strict = true);
34
        }
35 46
        return is_array($value) ? $value : [];
36
    }
37
38
    /**
39
     * @return array
40
     */
41 11
    public static function convertFromDotNotation(array $array)
42
    {
43 11
        $results = [];
44 11
        foreach ($array as $path => $value) {
45 11
            $results = static::set($results, $path, $value);
46
        }
47 11
        return $results;
48
    }
49
50
    /**
51
     * @param mixed $value
52
     * @param mixed $callback
53
     * @return array
54
     */
55 43
    public static function convertFromString($value, $callback = null)
56
    {
57 43
        if (is_scalar($value)) {
58 42
            $value = array_map('trim', explode(',', Cast::toString($value)));
59
        }
60 43
        $callback = Helper::ifEmpty(Cast::toString($callback), Helper::class.'::isNotEmpty');
61 43
        return static::reindex(array_filter((array) $value, $callback));
62
    }
63
64
    /**
65
     * @param bool $flattenValue
66
     * @param string $prefix
67
     * @return array
68
     */
69 8
    public static function flatten(array $array, $flattenValue = false, $prefix = '')
70
    {
71 8
        $result = [];
72 8
        foreach ($array as $key => $value) {
73 1
            $newKey = ltrim($prefix.'.'.$key, '.');
74 1
            if (static::isIndexedAndFlat($value)) {
75
                $value = Helper::ifTrue(!$flattenValue, $value, function () use ($value) {
76 1
                    return '['.implode(', ', $value).']';
77 1
                });
78 1
            } elseif (is_array($value)) {
79 1
                $result = array_merge($result, static::flatten($value, $flattenValue, $newKey));
80 1
                continue;
81
            }
82 1
            $result[$newKey] = $value;
83
        }
84 8
        return $result;
85
    }
86
87
    /**
88
     * Get a value from an array of values using a dot-notation path as reference.
89
     * @param mixed $data
90
     * @param string|int $path
91
     * @param mixed $fallback
92
     * @return mixed
93
     */
94 30
    public static function get($data, $path = '', $fallback = '')
95
    {
96 30
        $data = static::consolidate($data);
97 30
        $keys = explode('.', $path);
98 30
        $result = $fallback;
99 30
        foreach ($keys as $key) {
100 30
            if (!isset($data[$key])) {
101 27
                return $fallback;
102
            }
103 30
            if (is_object($data[$key])) {
104 7
                $result = $data[$key];
105 7
                $data = static::consolidate($result);
106 7
                continue;
107
            }
108 30
            $result = $data[$key];
109 30
            $data = $result;
110
        }
111 30
        return $result;
112
    }
113
114
    /**
115
     * @param string|int $key
116
     * @return array
117
     */
118 1
    public static function insertAfter($key, array $array, array $insert)
119
    {
120 1
        return static::insert($array, $insert, $key, 'after');
121
    }
122
123
    /**
124
     * @param string|int $key
125
     * @return array
126
     */
127 1
    public static function insertBefore($key, array $array, array $insert)
128
    {
129 1
        return static::insert($array, $insert, $key, 'before');
130
    }
131
132
    /**
133
     * @param string|int $key
134
     * @param string $position
135
     * @return array
136
     */
137 2
    public static function insert(array $array, array $insert, $key, $position = 'before')
138
    {
139 2
        $keyPosition = array_search($key, array_keys($array));
140 2
        if (false !== $keyPosition) {
141 2
            $keyPosition = Cast::toInt($keyPosition);
142 2
            if ('after' == $position) {
143 1
                ++$keyPosition;
144
            }
145 2
            $result = array_slice($array, 0, $keyPosition);
146 2
            $result = array_merge($result, $insert);
147 2
            return array_merge($result, array_slice($array, $keyPosition));
148
        }
149 2
        return array_merge($array, $insert);
150
    }
151
152
    /**
153
     * @param mixed $array
154
     * @return bool
155
     */
156 55
    public static function isIndexedAndFlat($array)
157
    {
158 55
        if (!is_array($array) || array_filter($array, 'is_array')) {
159 50
            return false;
160
        }
161 54
        return wp_is_numeric_array($array);
162
    }
163
164
    /**
165
     * @param bool $prefixed
166
     * @return array
167
     */
168 16
    public static function prefixKeys(array $values, $prefix = '_', $prefixed = true)
169
    {
170 16
        $trim = Helper::ifTrue($prefixed, $prefix, '');
171 16
        $prefixed = [];
172 16
        foreach ($values as $key => $value) {
173 3
            $key = trim($key);
174 3
            if (0 === strpos($key, $prefix)) {
175 3
                $key = substr($key, strlen($prefix));
176
            }
177 3
            $prefixed[$trim.$key] = $value;
178
        }
179 16
        return $prefixed;
180
    }
181
182
    /**
183
     * @param array $array
184
     * @param mixed $value
185
     * @param mixed $key
186
     * @return array
187
     */
188 15
    public static function prepend($array, $value, $key = null)
189
    {
190 15
        if (!is_null($key)) {
191 8
            return [$key => $value] + $array;
192
        }
193 13
        array_unshift($array, $value);
194 13
        return $array;
195
    }
196
197
    /**
198
     * @param mixed $array
199
     * @return array
200
     */
201 44
    public static function reindex($array)
202
    {
203 44
        return static::isIndexedAndFlat($array) ? array_values($array) : $array;
204
    }
205
206
    /**
207
     * Unset a value from an array of values using a dot-notation path as reference.
208
     * @param mixed $data
209
     * @param string $path
210
     * @return array
211
     */
212 8
    public static function remove($data, $path = '')
213
    {
214 8
        $data = static::consolidate($data);
215 8
        $keys = explode('.', $path);
216 8
        $last = array_pop($keys);
217 8
        $pointer = &$data;
218 8
        foreach ($keys as $key) {
219 8
            if (is_array(static::get($pointer, $key))) {
220 8
                $pointer = &$pointer[$key];
221
            }
222
        }
223 8
        unset($pointer[$last]);
224 8
        return $data;
225
    }
226
227
    /**
228
     * @return array
229
     */
230 2
    public static function removeEmptyValues(array $array)
231
    {
232 2
        $result = [];
233 2
        foreach ($array as $key => $value) {
234 2
            if (Helper::isEmpty($value)) {
235 2
                continue;
236
            }
237
            $result[$key] = Helper::ifTrue(!is_array($value), $value, function () use ($value) {
238 1
                return static::removeEmptyValues($value);
239 2
            });
240
        }
241 2
        return $result;
242
    }
243
244
    /**
245
     * Search a multidimensional array by key value
246
     * @param mixed $needle
247
     * @param array $haystack
248
     * @param int|string $key
249
     * @return array|false
250
     */
251 12
    public static function searchByKey($needle, $haystack, $key)
252
    {
253 12
        if (!is_array($haystack) || array_diff_key($haystack, array_filter($haystack, 'is_array'))) {
254
            return false;
255
        }
256 12
        $index = array_search($needle, wp_list_pluck($haystack, $key));
257 12
        if (false !== $index) {
258
            return $haystack[$index];
259
        }
260 12
        return false;
261
    }
262
263
    /**
264
     * Set a value to an array of values using a dot-notation path as reference.
265
     * @param mixed $data
266
     * @param string $path
267
     * @param mixed $value
268
     * @return array
269
     */
270 25
    public static function set($data, $path, $value)
271
    {
272 25
        $token = strtok($path, '.');
273 25
        $ref = &$data;
274 25
        while (false !== $token) {
275 25
            if (is_object($ref)) {
276 1
                $ref = &$ref->$token;
277
            } else {
278 25
                $ref = static::consolidate($ref);
279 25
                $ref = &$ref[$token];
280
            }
281 25
            $token = strtok('.');
282
        }
283 25
        $ref = $value;
284 25
        return $data;
285
    }
286
287
    /**
288
     * @return array
289
     */
290 27
    public static function unique(array $values)
291
    {
292
        return Helper::ifTrue(!static::isIndexedAndFlat($values), $values, function () use ($values) {
293 27
            return array_filter(array_unique($values));
294 27
        });
295
    }
296
297
    /**
298
     * @param array|string $values
299
     * @return array
300
     */
301 26
    public static function uniqueInt($values)
302
    {
303 26
        $values = array_filter(static::convertFromString($values), 'is_numeric');
304 26
        return static::reindex(static::unique(array_values(array_map('absint', $values))));
305
    }
306
307
    /**
308
     * @return array
309
     */
310 15
    public static function unprefixKeys(array $values, $prefix = '_')
311
    {
312 15
        return static::prefixKeys($values, $prefix, false);
313
    }
314
}
315