PathPatternGenerator::generate()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 12
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 20
rs 9.5555
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 PathPatternGenerator
10
{
11
    public static function generate(string $path): string
12
    {
13
        if ($path === '') {
14
            return '#^/?$#';
15
        }
16
17
        $parts = explode('/', $path);
18
        $pattern = '';
19
20
        foreach ($parts as $part) {
21
            if (preg_match(RouteParams::MANDATORY_PARAM_PATTERN, $part)) {
22
                $pattern .= '/([^\/]+)';
23
            } elseif (preg_match(RouteParams::OPTIONAL_PARAM_PATTERN, $part)) {
24
                $pattern .= '/?([^\/]+)?';
25
            } else {
26
                $pattern .= '/' . $part;
27
            }
28
        }
29
30
        return '#^/' . ltrim($pattern, '/') . '$#';
31
    }
32
}
33