Helper::getPostId()   B
last analyzed

Complexity

Conditions 9
Paths 13

Size

Total Lines 33
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 9.4867

Importance

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