Passed
Push — master ( 23a3ca...8a12fc )
by Alexey
03:27
created

RoutePathProcessor::processOptionalPlaceholders()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.125

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 4
cp 0.5
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1.125
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
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}}";
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $placeholder instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $regex instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
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->getPath())
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
58
}