-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathRouter.php
More file actions
153 lines (121 loc) · 4.47 KB
/
Copy pathRouter.php
File metadata and controls
153 lines (121 loc) · 4.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
<?php declare(strict_types=1);
namespace Bref\DevServer;
use Psr\Http\Message\ServerRequestInterface;
use function is_array;
/**
* Reproduces API Gateway routing for local development.
*
* @internal
*/
class Router
{
public static function fromServerlessConfig(array $serverlessConfig): self
{
$routes = [];
foreach ($serverlessConfig['functions'] as $function) {
$pattern = $function['events'][0]['httpApi'] ?? null;
if (! $pattern) {
continue;
}
if (is_string($pattern)) {
$pattern = array_combine(['method', 'path'], array_pad(explode(' ', $pattern, 2), 2, '*'));
}
$pattern = self::patternToString($pattern);
$routes[$pattern] = $function['handler'];
}
return new self($routes);
}
private static function patternToString(array $pattern): string
{
$method = $pattern['method'] ?? '*';
$path = $pattern['path'] ?? '*';
// Special "any" method MUST be converted to star.
if (strtolower($method) === 'any') {
$method = '*';
}
// Alternative catch-all MUST be converted to standard catch-all.
if ($method === '*' && $path === '*') {
return '*';
}
return $method . ' ' . $path;
}
/** @var array<string,string> */
private array $routes;
/**
* @param array<string,string> $routes
*/
public function __construct(array $routes)
{
$this->routes = $routes;
}
/**
* @return array{0: ?string, 1: ServerRequestInterface}
*/
public function match(ServerRequestInterface $request): array
{
foreach ($this->routes as $pattern => $handler) {
// Catch-all
if ($pattern === '*') return [$handler, $request];
[$httpMethod, $pathPattern] = explode(' ', $pattern);
if ($this->matchesMethod($request, $httpMethod) && $this->matchesPath($request, $pathPattern)) {
$request = $this->addPathParameters($request, $pathPattern);
return [$handler, $request];
}
}
// No route matched
return [null, $request];
}
private function matchesMethod(ServerRequestInterface $request, string $method): bool
{
$method = strtolower($method);
return ($method === '*') || ($method === strtolower($request->getMethod()));
}
private function matchesPath(ServerRequestInterface $request, string $pathPattern): bool
{
$requestPath = $request->getUri()->getPath();
// No path parameter
if (! str_contains($pathPattern, '{')) {
return $requestPath === $pathPattern;
}
$pathRegex = $this->patternToRegex($pathPattern);
return preg_match($pathRegex, $requestPath) === 1;
}
private function addPathParameters(ServerRequestInterface $request, mixed $pathPattern): ServerRequestInterface
{
$requestPath = $request->getUri()->getPath();
// No path parameter
if (! str_contains($pathPattern, '{')) {
return $request;
}
$pathRegex = $this->patternToRegex($pathPattern);
preg_match($pathRegex, $requestPath, $matches);
foreach ($matches as $name => $value) {
$request = $request->withAttribute((string) $name, $value);
}
return $request;
}
private function patternToRegex(string $pathPattern): string
{
// Match to find all the parameter names
$matchRegex = '#^' . preg_replace('/{[^}]+}/', '([^/]+)', $pathPattern) . '$#';
preg_match($matchRegex, $pathPattern, $matches);
// Ignore the global match of the string
unset($matches[0]);
/*
* We will replace all parameter paths with a *name* group.
* Essentially:
* - `/{root}` will be replaced to `/(?<root>[^/]+)` (i.e. `([^/]+)` named "root")
*/
$patterns = [];
$replacements = [];
foreach ($matches as $position => $parameterName) {
$patterns[$position] = "#$parameterName#";
// Remove `{` and `}` delimiters
$parameterName = substr($parameterName, 1, -1);
// The `?<$parameterName>` syntax lets us name the capturing group
$replacements[$position] = "(?<$parameterName>[^/]+)";
}
$regex = preg_replace($patterns, $replacements, $pathPattern);
return '#^' . $regex . '$#';
}
}