Passed
Push — master ( 197c27...f2cc15 )
by Paul
22:24 queued 07:48
created

Helper::remoteStatusCheck()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2.0078

Importance

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