PathValidator::hasValidFormat()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 15
ccs 11
cts 11
cp 1
crap 4
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 109
    public static function isValid(string $path): bool
12
    {
13 109
        if ($path === '/') {
14 2
            return true;
15
        }
16
17 109
        if (!self::hasValidFormat($path)) {
18 1
            return false;
19
        }
20
21 108
        return self::hasValidParameterOrder($path);
22 1
    }
23
24
    private static function hasValidFormat(string $path): bool
25 107
    {
26 1
        if ($path === '') {
27
            return false;
28
        }
29 106
30 106
        if (str_starts_with($path, '/')) {
31
            return false;
32 106
        }
33 106
34 1
        if (str_ends_with($path, '/')) {
35 106
            return false;
36 10
        }
37 106
38 2
        return !self::hasEmptyParts($path);
39
    }
40
41
    private static function hasEmptyParts(string $path): bool
42 103
    {
43
        $parts = explode('/', $path);
44
45
        foreach ($parts as $part) {
46
            if (!$part) {
47
                return true;
48
            }
49
        }
50
51
        return false;
52
    }
53
54
    private static function hasValidParameterOrder(string $path): bool
55
    {
56
        $parts = explode('/', $path);
57
        $optionalParamFound = false;
58
59
        foreach ($parts as $part) {
60
            if (!$part) { // Empty part found
61
                return false;
62
            }
63
            if (preg_match(RouteParams::OPTIONAL_PARAM_PATTERN, $part)) { // Optional argument found
64
                $optionalParamFound = true;
65
            } elseif ($optionalParamFound) { // Mandatory argument or static part found after an optional argument
66
                return false;
67
            }
68
        }
69
70
        return true;
71
    }
72
}
73