|
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 |
|
|
|
|
|
|
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
|
|
|
|