matchRequestPathAgainstWhitelist()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 9
ccs 2
cts 2
cp 1
crap 3
rs 10
1
<?php
2
3
namespace MediaMonks\RestApi\Request;
4
5
use Symfony\Component\HttpFoundation\Request;
6
use Symfony\Component\HttpKernel\HttpKernelInterface;
7
8
class RegexRequestMatcher extends AbstractRequestMatcher
9
{
10
    public function __construct(protected array $whitelist = [], protected array $blacklist = [])
11
    {
12
13
    }
14
15
    public function matches(Request $request, ?int $requestType = HttpKernelInterface::MAIN_REQUEST): bool
16
    {
17
        if ($requestType !== HttpKernelInterface::MAIN_REQUEST) {
18
            return false;
19
        }
20
21
        if ($this->matchPreviouslyMatchedRequest($request)) {
22
            return true;
23
        }
24 10
25
        if (!$this->matchRequestPathAgainstLists($request->getPathInfo())) {
26 10
            return false;
27 10
        }
28 10
29
        $this->markRequestAsMatched($request);
30
31
        return true;
32
    }
33
34
    protected function markRequestAsMatched(Request $request)
35 8
    {
36
        $request->attributes->set(self::ATTRIBUTE_MATCHED, true);
37 8
    }
38 4
39
    protected function matchPreviouslyMatchedRequest(Request $request): bool
40
    {
41 8
        return $request->attributes->getBoolean(self::ATTRIBUTE_MATCHED);
42 2
    }
43
44
    protected function matchRequestPathAgainstLists($requestPath): bool
45 8
    {
46 6
        if ($this->matchRequestPathAgainstBlacklist($requestPath)) {
47
            return false;
48
        }
49 5
50
        if ($this->matchRequestPathAgainstWhitelist($requestPath)) {
51 5
            return true;
52
        }
53
54
        return false;
55
    }
56
57 5
    protected function matchRequestPathAgainstBlacklist(string $requestPath): bool
58
    {
59 5
        foreach ($this->blacklist as $regex) {
60 5
            if (preg_match($regex, $requestPath)) {
61
                return true;
62
            }
63
        }
64
65
        return false;
66 8
    }
67
68 8
    protected function matchRequestPathAgainstWhitelist(string $requestPath): bool
69
    {
70
        foreach ($this->whitelist as $regex) {
71
            if (preg_match($regex, $requestPath)) {
72
                return true;
73
            }
74
        }
75 8
76
        return false;
77 8
    }
78
}
79