Test Failed
Push — develop ( e65255...277958 )
by Paul
10:13
created

Helper::svg()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
eloc 17
c 0
b 0
f 0
dl 0
loc 25
rs 9.0777
ccs 0
cts 0
cp 0
cc 6
nc 8
nop 2
crap 42
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 = glsr()->filterInt('assigned_users/profile_id', 0);
185
            if (empty($profileId) && is_author()) {
186
                $profileId = get_queried_object_id(); // is_author() ensures this is a User ID
187
            }
188
            return $profileId;
189 6
        }
190
        if ('user_id' === $user) {
191
            return glsr()->filterInt('assigned_users/user_id', get_current_user_id());
192 6
        }
193 6
        if (is_numeric($user)) {
194 6
            $user = get_user_by('id', $user);
195
            return Arr::getAs('int', $user, 'ID');
196 1
        }
197 1
        if (is_string($user)) {
198 1
            $user = get_user_by('login', sanitize_user($user, true));
199
            return Arr::getAs('int', $user, 'ID');
200 1
        }
201
        return 0;
202
    }
203
204
    /**
205
     * @param mixed $value
206
     * @param mixed $fallback
207
     *
208
     * @return mixed
209 135
     */
210
    public static function ifEmpty($value, $fallback, $strict = false)
211 135
    {
212 135
        $isEmpty = $strict ? empty($value) : static::isEmpty($value);
213
        return $isEmpty ? $fallback : $value;
214
    }
215
216
    /**
217
     * @param mixed $ifTrue
218
     * @param mixed $ifFalse
219
     *
220
     * @return mixed
221 181
     */
222
    public static function ifTrue(bool $condition, $ifTrue, $ifFalse = null)
223 181
    {
224
        return $condition ? static::runClosure($ifTrue) : static::runClosure($ifFalse);
225
    }
226
227
    /**
228
     * @param mixed      $value
229
     * @param string|int $min
230
     * @param string|int $max
231 6
     */
232
    public static function inRange($value, $min, $max): bool
233 6
    {
234 6
        $inRange = filter_var($value, FILTER_VALIDATE_INT, ['options' => [
235 6
            'min_range' => intval($min),
236 6
            'max_range' => intval($max),
237 6
        ]]);
238
        return false !== $inRange;
239
    }
240
241
    /**
242
     * @param mixed $value
243 222
     */
244
    public static function isEmpty($value): bool
245 222
    {
246 201
        if (is_string($value)) {
247
            return '' === trim($value);
248 219
        }
249
        return !is_numeric($value) && !is_bool($value) && empty($value);
250
    }
251
252
    /**
253
     * @param int|string $value
254
     * @param int|string $compareWithValue
255 45
     */
256
    public static function isGreaterThan($value, $compareWithValue): bool
257 45
    {
258
        return static::compareVersions($value, $compareWithValue, '>');
259
    }
260
261
    /**
262
     * @param int|string $value
263
     * @param int|string $compareWithValue
264 1
     */
265
    public static function isGreaterThanOrEqual($value, $compareWithValue): bool
266 1
    {
267
        return static::compareVersions($value, $compareWithValue, '>=');
268
    }
269
270
    /**
271
     * @param int|string $value
272
     * @param int|string $compareWithValue
273 1
     */
274
    public static function isLessThan($value, $compareWithValue): bool
275 1
    {
276
        return static::compareVersions($value, $compareWithValue, '<');
277
    }
278
279
    /**
280
     * @param int|string $value
281
     * @param int|string $compareWithValue
282 1
     */
283
    public static function isLessThanOrEqual($value, $compareWithValue): bool
284 1
    {
285
        return static::compareVersions($value, $compareWithValue, '<=');
286
    }
287 25
288
    public static function isLocalServer(): bool
289 25
    {
290 25
        $host = static::ifEmpty(filter_input(INPUT_SERVER, 'HTTP_HOST'), 'localhost');
291 25
        $ipAddress = static::ifEmpty(filter_input(INPUT_SERVER, 'SERVER_ADDR'), '::1');
292 25
        $result = false;
293
        if (in_array($ipAddress, ['127.0.0.1', '::1'])
294 25
            || !mb_strpos($host, '.')
295 25
            || in_array(mb_strrchr($host, '.'), ['.test', '.testing', '.local', '.localhost', '.localdomain'])) {
296
            $result = true;
297 25
        }
298
        return glsr()->filterBool('is-local-server', $result);
299
    }
300
301
    /**
302
     * @param mixed $value
303 135
     */
304
    public static function isNotEmpty($value): bool
305 135
    {
306
        return !static::isEmpty($value);
307
    }
308
309
    /**
310
     * @return int|false
311 25
     */
312
    public static function remoteStatusCheck(string $url)
313 25
    {
314 25
        $response = wp_safe_remote_head($url, [
315 25
            'sslverify' => !static::isLocalServer(),
316 25
        ]);
317 25
        if (!is_wp_error($response)) {
318
            return $response['response']['code'];
319
        }
320
        return false;
321
    }
322
323
    /**
324
     * @param mixed $value
325
     *
326
     * @return mixed
327 181
     */
328
    public static function runClosure($value)
329 181
    {
330 179
        if ($value instanceof \Closure || (is_array($value) && is_callable($value))) {
331
            return call_user_func($value);
332 172
        }
333
        return $value;
334
    }
335
336
    public static function version(string $version, string $versionLevel = ''): string
337
    {
338
        $pattern = '/^v?(\d{1,5})(\.\d++)?(\.\d++)?(.+)?$/i';
339
        preg_match($pattern, $version, $matches);
340
        switch ($versionLevel) {
341
            case 'major':
342
                $result = Arr::get($matches, 1);
343
                break;
344
            case 'minor':
345
                $result = Arr::get($matches, 1).Arr::get($matches, 2);
346
                break;
347
            case 'patch':
348
                $result = Arr::get($matches, 1).Arr::get($matches, 2).Arr::get($matches, 3);
349
                break;
350
            default:
351
                $result = $version;
352
                break;
353
        }
354
        return $result;
355
    }
356
}
357