Test Failed
Push — main ( 6435b1...db043e )
by Paul
16:23 queued 07:02
created

Helper::getUserId()   B

Complexity

Conditions 9
Paths 8

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 19.125

Importance

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