Helper   F
last analyzed

Complexity

Total Complexity 72

Size/Duplication

Total Lines 350
Duplicated Lines 0 %

Test Coverage

Coverage 78.89%

Importance

Changes 0
Metric Value
wmc 72
eloc 154
dl 0
loc 350
ccs 142
cts 180
cp 0.7889
rs 2.64
c 0
b 0
f 0

24 Methods

Rating   Name   Duplication   Size   Complexity  
A runClosure() 0 6 4
A buildClassName() 0 10 3
A compareVersions() 0 5 2
A getPageNumber() 0 10 3
A filterInputArray() 0 7 4
A getIpAddress() 0 32 4
A buildMethodName() 0 4 1
B getPostId() 0 33 9
A inRange() 0 7 1
A filterInput() 0 10 4
A ifEmpty() 0 4 3
A isGreaterThanOrEqual() 0 3 1
A isLessThanOrEqual() 0 3 1
A isGreaterThan() 0 3 1
A remoteStatusCheck() 0 9 2
A ifTrue() 0 3 2
A isLocalIpAddress() 0 6 2
A isLessThan() 0 3 1
B getUserId() 0 26 8
A isEmpty() 0 6 4
A version() 0 19 4
A isNotEmpty() 0 3 1
A getTermTaxonomyId() 0 13 3
A isLocalServer() 0 11 4

How to fix   Complexity   

Complex Class

Complex classes like Helper 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 Helper, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace GeminiLabs\SiteReviews;
4
5
use GeminiLabs\SiteReviews\Helpers\Arr;
6
use GeminiLabs\SiteReviews\Helpers\Cast;
7
use GeminiLabs\SiteReviews\Helpers\Str;
8
use GeminiLabs\SiteReviews\Helpers\Url;
9
use GeminiLabs\Vectorface\Whip\Whip;
10
11
class Helper
12
{
13
    /**
14
     * @param array|string $name
15
     */
16 210
    public static function buildClassName($name, string $path = ''): string
17
    {
18 210
        if (is_array($name)) {
19 209
            $name = implode('-', $name);
20
        }
21 210
        $className = Str::camelCase($name);
22 210
        $path = ltrim(str_replace(__NAMESPACE__, '', $path), '\\');
23 210
        return !empty($path)
24 210
            ? __NAMESPACE__.'\\'.$path.'\\'.$className
25 210
            : $className;
26
    }
27
28 219
    public static function buildMethodName(string ...$name): string
29
    {
30 219
        $name = implode('-', $name);
31 219
        return lcfirst(Str::camelCase($name));
32
    }
33
34
    /**
35
     * @param int|string $version1
36
     * @param int|string $version2
37
     */
38 5
    public static function compareVersions($version1, $version2, string $operator = '='): bool
39
    {
40 5
        $version1 = implode('.', array_pad(explode('.', $version1), 3, 0));
41 5
        $version2 = implode('.', array_pad(explode('.', $version2), 3, 0));
42 5
        return version_compare($version1, $version2, $operator ?: '=');
43
    }
44
45
    /**
46
     * @return mixed
47
     */
48 1
    public static function filterInput(string $key, array $request = [])
49
    {
50 1
        if (isset($request[$key])) {
51
            return $request[$key];
52
        }
53 1
        $variable = filter_input(INPUT_POST, $key);
54 1
        if (is_null($variable) && isset($_POST[$key])) {
55 1
            $variable = $_POST[$key];
56
        }
57 1
        return $variable;
58
    }
59
60 1
    public static function filterInputArray(string $key): array
61
    {
62 1
        $variable = filter_input(INPUT_POST, $key, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
63 1
        if (empty($variable) && !empty($_POST[$key]) && is_array($_POST[$key])) {
64 1
            $variable = $_POST[$key];
65
        }
66 1
        return Cast::toArray($variable);
67
    }
68
69 17
    public static function getIpAddress(): string
70
    {
71 17
        $setting = glsr()->args(get_option(glsr()->prefix.'ip_proxy'));
72 17
        $proxyHeader = $setting->sanitize('proxy_http_header', 'id');
73 17
        $trustedProxies = $setting->sanitize('trusted_proxies', 'text-multiline');
74 17
        $trustedProxies = explode("\n", $trustedProxies);
75 17
        $whitelist = [];
76 17
        if (!empty($proxyHeader)) {
77
            $ipv4 = array_filter($trustedProxies, function ($range) {
78
                [$ip] = explode('/', $range);
79
                return !empty(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4));
80
            });
81
            $ipv6 = array_filter($trustedProxies, function ($range) {
82
                [$ip] = explode('/', $range);
83
                return !empty(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6));
84
            });
85
            $whitelist[$proxyHeader] = [
86
                Whip::IPV4 => $ipv4,
87
                Whip::IPV6 => $ipv6,
88
            ];
89
        }
90 17
        $whitelist = glsr()->filterArray('whip/whitelist', $whitelist);
91 17
        $whip = new Whip(Whip::REMOTE_ADDR | Whip::CUSTOM_HEADERS, $whitelist);
92 17
        if (!empty($proxyHeader)) {
93
            $whip->addCustomHeader($proxyHeader);
94
        }
95 17
        glsr()->action('whip', $whip);
96 17
        if (false !== ($clientAddress = $whip->getValidIpAddress())) {
97 17
            return (string) $clientAddress;
98
        }
99
        glsr_log()->error('Unable to detect IP address, please see the FAQ page for a possible solution.');
100
        return 'unknown';
101
    }
102
103 1
    public static function getPageNumber(?string $fromUrl = null, ?int $fallback = 1): int
104
    {
105 1
        $pagedQueryVar = glsr()->constant('PAGED_QUERY_VAR');
106 1
        $pageNum = empty($fromUrl)
107 1
            ? filter_input(INPUT_GET, $pagedQueryVar, FILTER_VALIDATE_INT)
108 1
            : filter_var(Url::query($fromUrl, $pagedQueryVar), FILTER_VALIDATE_INT);
109 1
        if (empty($pageNum)) {
110 1
            $pageNum = (int) $fallback;
111
        }
112 1
        return max(1, $pageNum);
113
    }
114
115
    /**
116
     * @param mixed $post
117
     */
118 5
    public static function getPostId($post): int
119
    {
120 5
        if (empty($post)) {
121 1
            return 0;
122
        }
123 5
        if (is_numeric($post) || $post instanceof \WP_Post) {
124 5
            $post = get_post($post);
125
        }
126 5
        if ($post instanceof \WP_Post) {
127 5
            return $post->ID;
128
        }
129 1
        if ('parent_id' === $post) {
130
            $parentId = (int) wp_get_post_parent_id(intval(get_the_ID()));
131
            return glsr()->filterInt('assigned_posts/parent_id', $parentId);
132
        }
133 1
        if ('post_id' === $post) {
134
            $postId = (int) get_the_ID();
135
            return glsr()->filterInt('assigned_posts/post_id', $postId);
136
        }
137 1
        if (is_string($post)) {
138 1
            $post = sanitize_text_field($post);
139 1
            $parts = explode(':', $post);
140 1
            if (2 === count($parts)) {
141 1
                $posts = get_posts([
142 1
                    'fields' => 'ids',
143 1
                    'post_name__in' => [$parts[1]],
144 1
                    'post_type' => $parts[0],
145 1
                    'posts_per_page' => 1,
146 1
                ]);
147 1
                return Arr::getAs('int', $posts, 0);
148
            }
149
        }
150 1
        return 0;
151
    }
152
153
    /**
154
     * @param mixed $term
155
     */
156 5
    public static function getTermTaxonomyId($term): int
157
    {
158 5
        if ($term instanceof \WP_Term) {
159
            return $term->term_id;
160
        }
161 5
        if (is_numeric($term)) {
162 5
            $term = Cast::toInt($term);
163
        } else {
164 1
            $term = sanitize_text_field(Cast::toString($term));
165
        }
166 5
        $tt = term_exists($term, glsr()->taxonomy);
167 5
        $ttid = Arr::getAs('int', $tt, 'term_id');
168 5
        return glsr()->filterInt('assigned_terms/term_id', $ttid, $term, glsr()->taxonomy);
169
    }
170
171
    /**
172
     * @param mixed $user
173
     */
174 5
    public static function getUserId($user): int
175
    {
176 5
        if ($user instanceof \WP_User) {
177
            return $user->ID;
178
        }
179 5
        if ('author_id' === $user) {
180
            $authorId = Cast::toInt(get_the_author_meta('ID'));
181
            return glsr()->filterInt('assigned_users/author_id', $authorId);
182
        }
183 5
        if ('profile_id' === $user) {
184
            $profileId = is_author() ? get_queried_object_id() : 0;
185
            return glsr()->filterInt('assigned_users/profile_id', $profileId);
186
        }
187 5
        if ('user_id' === $user) {
188
            $userId = get_current_user_id();
189
            return glsr()->filterInt('assigned_users/user_id', $userId);
190
        }
191 5
        if (is_numeric($user)) {
192 5
            $user = get_user_by('id', $user);
193 5
            return Arr::getAs('int', $user, 'ID');
194
        }
195 1
        if (is_string($user)) {
196 1
            $user = get_user_by('login', sanitize_user($user, true));
197 1
            return Arr::getAs('int', $user, 'ID');
198
        }
199 1
        return 0;
200
    }
201
202
    /**
203
     * @param mixed $value
204
     * @param mixed $fallback
205
     *
206
     * @return mixed
207
     */
208 139
    public static function ifEmpty($value, $fallback, $strict = false)
209
    {
210 139
        $isEmpty = $strict ? empty($value) : static::isEmpty($value);
211 139
        return $isEmpty ? $fallback : $value;
212
    }
213
214
    /**
215
     * @param mixed $ifTrue
216
     * @param mixed $ifFalse
217
     *
218
     * @return mixed
219
     */
220 186
    public static function ifTrue(bool $condition, $ifTrue, $ifFalse = null)
221
    {
222 186
        return $condition ? static::runClosure($ifTrue) : static::runClosure($ifFalse);
223
    }
224
225
    /**
226
     * @param mixed      $value
227
     * @param string|int $min
228
     * @param string|int $max
229
     */
230 6
    public static function inRange($value, $min, $max): bool
231
    {
232 6
        $inRange = filter_var($value, FILTER_VALIDATE_INT, ['options' => [
233 6
            'min_range' => intval($min),
234 6
            'max_range' => intval($max),
235 6
        ]]);
236 6
        return false !== $inRange;
237
    }
238
239
    /**
240
     * @param mixed $value
241
     */
242 228
    public static function isEmpty($value): bool
243
    {
244 228
        if (is_string($value)) {
245 207
            return '' === trim($value);
246
        }
247 222
        return !is_numeric($value) && !is_bool($value) && empty($value);
248
    }
249
250
    /**
251
     * @param int|string $value
252
     * @param int|string $compareWithValue
253
     */
254 1
    public static function isGreaterThan($value, $compareWithValue): bool
255
    {
256 1
        return static::compareVersions($value, $compareWithValue, '>');
257
    }
258
259
    /**
260
     * @param int|string $value
261
     * @param int|string $compareWithValue
262
     */
263 1
    public static function isGreaterThanOrEqual($value, $compareWithValue): bool
264
    {
265 1
        return static::compareVersions($value, $compareWithValue, '>=');
266
    }
267
268
    /**
269
     * @param int|string $value
270
     * @param int|string $compareWithValue
271
     */
272 1
    public static function isLessThan($value, $compareWithValue): bool
273
    {
274 1
        return static::compareVersions($value, $compareWithValue, '<');
275
    }
276
277
    /**
278
     * @param int|string $value
279
     * @param int|string $compareWithValue
280
     */
281 1
    public static function isLessThanOrEqual($value, $compareWithValue): bool
282
    {
283 1
        return static::compareVersions($value, $compareWithValue, '<=');
284
    }
285
286 17
    public static function isLocalIpAddress(string $ipAddress): bool
287
    {
288 17
        if (false !== filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)) {
289 17
            return in_array($ipAddress, ['127.0.0.1', '::1']);
290
        }
291
        return true;
292
    }
293
294 17
    public static function isLocalServer(): bool
295
    {
296 17
        $host = static::ifEmpty(filter_input(INPUT_SERVER, 'HTTP_HOST'), 'localhost');
297 17
        $ipAddress = static::ifEmpty(filter_input(INPUT_SERVER, 'SERVER_ADDR'), '::1');
298 17
        $result = false;
299 17
        if (static::isLocalIpAddress($ipAddress)
300 17
            || !mb_strpos($host, '.')
301 17
            || in_array(mb_strrchr($host, '.'), ['.test', '.testing', '.local', '.localhost', '.localdomain'])) {
302 17
            $result = true;
303
        }
304 17
        return glsr()->filterBool('is-local-server', $result);
305
    }
306
307
    /**
308
     * @param mixed $value
309
     */
310 139
    public static function isNotEmpty($value): bool
311
    {
312 139
        return !static::isEmpty($value);
313
    }
314
315
    /**
316
     * @return int|false
317
     */
318 17
    public static function remoteStatusCheck(string $url)
319
    {
320 17
        $response = wp_safe_remote_head($url, [
321 17
            'sslverify' => !static::isLocalServer(),
322 17
        ]);
323 17
        if (!is_wp_error($response)) {
324 17
            return $response['response']['code'];
325
        }
326
        return false;
327
    }
328
329
    /**
330
     * @param mixed $value
331
     *
332
     * @return mixed
333
     */
334 186
    public static function runClosure($value)
335
    {
336 186
        if ($value instanceof \Closure || (is_array($value) && is_callable($value))) {
337 186
            return call_user_func($value);
338
        }
339 175
        return $value;
340
    }
341
342 118
    public static function version(string $version, string $versionLevel = ''): string
343
    {
344 118
        $pattern = '/^v?(\d{1,5})(\.\d++)?(\.\d++)?(.+)?$/i';
345 118
        preg_match($pattern, $version, $matches);
346
        switch ($versionLevel) {
347 118
            case 'major':
348 118
                $result = Arr::get($matches, 1);
349 118
                break;
350
            case 'minor':
351
                $result = Arr::get($matches, 1).Arr::get($matches, 2);
352
                break;
353
            case 'patch':
354
                $result = Arr::get($matches, 1).Arr::get($matches, 2).Arr::get($matches, 3);
355
                break;
356
            default:
357
                $result = $version;
358
                break;
359
        }
360 118
        return $result;
361
    }
362
}
363