RouteCompiler::compileRoute()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 17
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 27
ccs 18
cts 18
cp 1
crap 3
rs 9.7
1
<?php
2
3
/**
4
 * It's free open-source software released under the MIT License.
5
 *
6
 * @author Anatoly Nekhay <[email protected]>
7
 * @copyright Copyright (c) 2018, Anatoly Nekhay
8
 * @license https://github.com/sunrise-php/http-router/blob/master/LICENSE
9
 * @link https://github.com/sunrise-php/http-router
10
 */
11
12
declare(strict_types=1);
13
14
namespace Sunrise\Http\Router\Helper;
15
16
use InvalidArgumentException;
17
18
use function addcslashes;
19
use function str_replace;
20
21
/**
22
 * @since 3.0.0
23
 */
24
final class RouteCompiler
25
{
26
    public const DEFAULT_VARIABLE_PATTERN = '[^/]+';
27
    public const EXPRESSION_DELIMITER = '#';
28
29
    /**
30
     * @param array<string, string> $patterns
31
     *
32
     * @return non-empty-string
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string.
Loading history...
33
     *
34
     * @throws InvalidArgumentException
35
     */
36 61
    public static function compileRoute(string $route, array $patterns = []): string
37
    {
38 61
        $variables = RouteParser::parseRoute($route);
39
40 61
        $search = [];
41 61
        $replace = [];
42 61
        foreach ($variables as $variable) {
43 14
            $search[] = $variable['statement'];
44 14
            $replace[] = '{' . $variable['name'] . '}';
45
        }
46
47 61
        $route = str_replace($search, $replace, $route);
48 61
        $route = addcslashes($route, '#$*+-.?[\]^|');
49 61
        $route = str_replace(['(', ')'], ['(?:', ')?'], $route);
50
51 61
        $search = [];
52 61
        $replace = [];
53 61
        foreach ($variables as $variable) {
54 14
            $pattern = $patterns[$variable['name']] ?? $variable['pattern'] ?? self::DEFAULT_VARIABLE_PATTERN;
55
56 14
            $search[] = '{' . $variable['name'] . '}';
57 14
            $replace[] = '(?<' . $variable['name'] . '>' . $pattern . ')';
58
        }
59
60 61
        $route = str_replace($search, $replace, $route);
61
62 61
        return '#^' . $route . '$#uD';
63
    }
64
}
65