Passed
Push — develop ( d01060...4713f8 )
by Paul
14:54
created

SanitizeUserId::userValue()   B

Complexity

Conditions 9
Paths 9

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 9

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 22
ccs 15
cts 15
cp 1
rs 8.0555
c 0
b 0
f 0
cc 9
nc 9
nop 1
crap 9
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Modules\Sanitizers;
4
5
use GeminiLabs\SiteReviews\Helpers\Arr;
6
7
class SanitizeUserId extends IntSanitizer
8
{
9
    public array $args;
10
    public $value;
11
    public array $values;
12
13 20
    public function __construct($value, array $args = [], array $values = [])
14
    {
15 20
        $args = array_pad($args, 2, ''); // minimum of 2 args
16 20
        $this->args = $args;
17 20
        $this->value = $this->userValue($value);
18 20
        $this->values = $values;
19
    }
20
21 20
    public function run(): int
22
    {
23 20
        if ($userId = $this->value()) {
24 2
            return $userId;
25
        }
26 20
        $fallback = $this->args[0];
27 20
        if ('current_user' === $fallback) {
28 18
            return $this->userValue(wp_get_current_user());
29
        }
30 20
        return $this->userValue($fallback);
31
    }
32
33
    /**
34
     * @param mixed $value
35
     */
36 20
    protected function userValue($value): int
37
    {
38 20
        if (empty($value)) {
39 20
            return 0;
40
        }
41 19
        if ($value instanceof \WP_User) {
42 18
            return $value->ID;
43
        }
44 2
        if ('user_id' === $value) {
45 1
            if (!defined('WP_IMPORTING')) {
46 1
                return get_current_user_id();
47
            }
48 2
        } elseif (is_numeric($value)) {
49 2
            if ($user = get_user_by('id', $value)) {
50 2
                return $user->ID;
51
            }
52 1
        } elseif (is_string($value)) {
53 1
            if ($user = get_user_by('login', sanitize_user($value, true))) {
54 1
                return $user->ID;
55
            }
56
        }
57 1
        return 0;
58
    }
59
}
60