|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Lepton\Routing; |
|
4
|
|
|
|
|
5
|
|
|
class UrlResolver |
|
6
|
|
|
{ |
|
7
|
|
|
|
|
8
|
|
|
public function __construct(private $pattern){} |
|
9
|
|
|
|
|
10
|
|
|
public function patternPrepare($pattern) |
|
11
|
|
|
{ |
|
12
|
|
|
$pattern = str_replace('?', '\?', $pattern); |
|
13
|
|
|
|
|
14
|
|
|
// if the type selector is not followed by a quantifier, than choose any length |
|
15
|
|
|
$pattern = preg_replace('/<([^{\d}]+?)(?!{[\d]+}):(.+?)>/', '<${1}+:${2}>', $pattern); |
|
16
|
|
|
|
|
17
|
|
|
// if the type selector is "int", match numbers |
|
18
|
|
|
$pattern = preg_replace('/<int([+{\d}]+?):(.+?)>/', '<\\d${1}:${2}>', $pattern); |
|
19
|
|
|
|
|
20
|
|
|
// if the type selector is "alpha" or "alnum" |
|
21
|
|
|
$pattern = preg_replace('/<(alpha|alnum)([+{\d}]+?):(.+?)>/', '<[[:${1}:]]${2}:${3}>', $pattern); |
|
22
|
|
|
|
|
23
|
|
|
// if there is no type selector, match anything but a / |
|
24
|
|
|
$pattern = preg_replace('/<([^:]+?)>/', '(?<${1}>[^/]+)', $pattern); |
|
25
|
|
|
|
|
26
|
|
|
// build regex |
|
27
|
|
|
$pattern = preg_replace('/<(.+?):(.+?)>/', '(?<${2}>${1})', $pattern); |
|
28
|
|
|
|
|
29
|
|
|
// replace slashes for regex |
|
30
|
|
|
$pattern = str_replace('/', '\/', $pattern); |
|
31
|
|
|
|
|
32
|
|
|
return $pattern; |
|
33
|
|
|
|
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
|
|
37
|
|
|
protected function patternMatch($pattern, &$parameters) |
|
38
|
|
|
{ |
|
39
|
|
|
$parameters = array(); |
|
40
|
|
|
|
|
41
|
|
|
|
|
42
|
|
|
$pattern = $this->patternPrepare($pattern); |
|
43
|
|
|
|
|
44
|
|
|
// perform actual match on request uri |
|
45
|
|
|
$is_match = preg_match(sprintf("/^%s$/", $pattern), $_SERVER['REQUEST_URI'], $parameters); |
|
46
|
|
|
|
|
47
|
|
|
// keep only string keys |
|
48
|
|
|
$parameters = array_filter($parameters, function ($k) { |
|
49
|
|
|
return is_string($k); |
|
50
|
|
|
}, ARRAY_FILTER_USE_KEY); |
|
51
|
|
|
return $is_match; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
public function match($pattern): bool|array |
|
55
|
|
|
{ |
|
56
|
|
|
$parameters = array(); |
|
57
|
|
|
|
|
58
|
|
|
return $this->patternMatch($pattern, $parameters) ? $parameters : false; |
|
59
|
|
|
|
|
60
|
|
|
|
|
61
|
|
|
|
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|