Passed
Push — develop ( c34e50...445d6d )
by Paul
06:42
created

BlacklistValidator   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 12
eloc 30
dl 0
loc 53
ccs 0
cts 35
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A performValidation() 0 10 3
A isValid() 0 11 1
A validateBlacklist() 0 17 6
A blacklist() 0 5 2
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Modules\Validator;
4
5
use GeminiLabs\SiteReviews\Database\OptionManager;
6
7
class BlacklistValidator extends ValidatorAbstract
8
{
9
    public function isValid(): bool
10
    {
11
        $target = implode("\n", array_filter([
12
            $this->request->name,
13
            $this->request->content,
14
            $this->request->email,
15
            $this->request->ip_address,
16
            $this->request->title,
17
        ]));
18
        $isValid = $this->validateBlacklist($target);
19
        return glsr()->filterBool('validate/blacklist', $isValid, $target, $this->request);
20
    }
21
22
    public function performValidation(): void
23
    {
24
        if (!$this->isValid()) {
25
            if ('reject' !== glsr_get_option('forms.blacklist.action')) {
26
                glsr()->sessionSet('form_blacklisted', true);
27
                return;
28
            }
29
            $this->fail(
30
                __('Your review cannot be submitted at this time.', 'site-reviews'),
31
                'Blacklisted submission detected.'
32
            );
33
        }
34
    }
35
36
    protected function blacklist(): string
37
    {
38
        return 'comments' === glsr_get_option('forms.blacklist.integration')
39
            ? trim(glsr(OptionManager::class)->wp('disallowed_keys'))
40
            : trim(glsr_get_option('forms.blacklist.entries'));
41
    }
42
43
    protected function validateBlacklist(string $target): bool
44
    {
45
        if (empty($blacklist = $this->blacklist())) {
46
            return true;
47
        }
48
        $lines = explode("\n", $blacklist);
49
        foreach ((array) $lines as $line) {
50
            $line = trim($line);
51
            if (empty($line) || 256 < strlen($line)) {
52
                continue;
53
            }
54
            $pattern = sprintf('#%s#iu', preg_quote($line, '#'));
55
            if (preg_match($pattern, $target)) {
56
                return false;
57
            }
58
        }
59
        return true;
60
    }
61
}
62