Passed
Pull Request — main (#35)
by
unknown
02:25
created

PathValidator::isPathValid()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Router\Validators;
6
7
use Gacela\Router\Entities\RouteParams;
8
9
final class PathValidator
10
{
11 105
    public function __invoke(string $path): bool
12
    {
13 105
        return $this->isPathValid($path);
14
    }
15
16 105
    protected function isPathValid(string $path): bool
17
    {
18 105
        return $this->isPathEmpty($path) || $this->isPathValidFormat($path);
19
    }
20
21 105
    private function isPathEmpty(string $path): bool
22
    {
23 105
        return $path === '';
24
    }
25
26 104
    private function isPathValidFormat(string $path): bool
27
    {
28 104
        return $this->isPathStartWithoutSlash($path)
29 104
            && $this->isPathEndWithoutSlash($path)
30 104
            && $this->areOptionalArgumentsAfterMandatoryArguments($path);
31
    }
32
33 104
    private function isPathStartWithoutSlash(string $path): bool
34
    {
35 104
        return $path[0] !== '/';
36
    }
37
38 104
    private function isPathEndWithoutSlash(string $path): bool
39
    {
40 104
        return $path[-1] !== '/';
41
    }
42
43 104
    private function areOptionalArgumentsAfterMandatoryArguments(string $path): bool
44
    {
45 104
        $parts = explode('/', $path);
46 104
        $optionalParamFound = false;
47
48 104
        foreach ($parts as $part) {
49 104
            if (preg_match(RouteParams::OPTIONAL_PARAM_PATTERN, $part)) {
50 10
                $optionalParamFound = true;
51
            } else {
52 104
                if ($optionalParamFound) {
53
                    // Mandatory argument or static part found after an optional argument
54 2
                    return false;
55
                }
56
            }
57
        }
58
59 102
        return true;
60
    }
61
}
62