RoutePathProcessor   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 58.81%

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 1
dl 0
loc 45
ccs 10
cts 17
cp 0.5881
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A addPattern() 0 6 1
A process() 0 8 1
A processOptionalPlaceholders() 0 4 1
1
<?php declare(strict_types = 1);
2
3
namespace Venta\Routing;
4
5
use Venta\Contracts\Routing\Route as RouteContract;
6
use Venta\Contracts\Routing\RoutePathProcessor as RoutePathProcessorContract;
7
8
/**
9
 * Class RoutePathProcessor
10
 *
11
 * @package Venta\Routing
12
 */
13
final class RoutePathProcessor implements RoutePathProcessorContract
14
{
15
16
    /**
17
     * Patterns to apply to route path: [pattern => replacement].
18
     *
19
     * @var string[]
20
     */
21
    private $patterns = [];
22
23
    /**
24
     * @inheritDoc
25
     */
26 2
    public function addPattern(string $placeholder, string $regex): RoutePathProcessorContract
27
    {
28 2
        $this->patterns["/{{$placeholder}}/"] = "{{$placeholder}:{$regex}}";
29
30 2
        return $this;
31
    }
32
33
    /**
34
     * @inheritDoc
35
     */
36 2
    public function process(RouteContract $route): RouteContract
37
    {
38 2
        return $route->withPath(preg_replace(
39 2
            array_keys($this->patterns),
40 2
            array_values($this->patterns),
41 2
            $this->processOptionalPlaceholders($route->path())
42
        ));
43
    }
44
45
    /**
46
     * Replaces {?placeholder} with [{placeholder}] FastRoute syntax.
47
     * Respects following segments by adding ] to the end.
48
     *
49
     * @param string $path
50
     * @return string
51
     */
52 2
    private function processOptionalPlaceholders(string $path): string
53
    {
54 2
        return preg_replace('/{\?(.+?)}/', '[{$1}', $path, -1, $count) . str_repeat(']', $count);
55
    }
56
57
}