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

SanitizeUserEmail::userValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Modules\Sanitizers;
4
5
use GeminiLabs\SiteReviews\Helpers\Cast;
6
7
class SanitizeUserEmail extends StringSanitizer
8
{
9
    public array $args;
10
    public $value;
11
    public array $values;
12
13 27
    public function __construct($value, array $args = [], array $values = [])
14
    {
15 27
        $args = array_pad($args, 2, ''); // minimum of 2 args
16 27
        $this->args = $args;
17 27
        $this->value = $this->userValue($value);
18 27
        $this->values = $values;
19
    }
20
21 27
    public function run(): string
22
    {
23 27
        $value = $this->sanitizeValue($this->value()); // allow any valid email value
24 27
        if (defined('WP_IMPORTING')) {
25
            return $value;
26
        }
27 27
        if (!empty($value)) {
28 19
            return $value;
29
        }
30 14
        $fallback = Cast::toString($this->args[0]); // try the fallback value
31 14
        if ('current_user' === $fallback) {
32 2
            $fallback = $this->userValue(wp_get_current_user());
33
        }
34 14
        return $this->sanitizeValue($fallback);
35
    }
36
37 27
    protected function sanitizeValue(string $value): string
38
    {
39 27
        return (new SanitizeEmail($value))->run();
40
    }
41
42
    /**
43
     * @param mixed $user
44
     */
45 27
    protected function userValue($user): string
46
    {
47 27
        if (!$user instanceof \WP_User) {
48 19
            return Cast::toString($user);
49
        }
50 14
        if (!$user->exists()) {
51 12
            return '';
52
        }
53 2
        return $user->user_email;
54
    }
55
}
56