-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
375 lines (317 loc) · 9.65 KB
/
Router.php
File metadata and controls
375 lines (317 loc) · 9.65 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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
<?php
/**
* @author : Jakiboy
* @package : FloatPHP
* @subpackage : Classes Http Component
* @version : 1.5.x
* @copyright : (c) 2018 - 2025 Jihad Sinnaour <me@jihadsinnaour.com>
* @link : https://floatphp.com
* @license : MIT
*
* This file is a part of FloatPHP Framework.
*/
declare(strict_types=1);
namespace FloatPHP\Classes\Http;
use FloatPHP\Classes\Filesystem\{TypeCheck, Stringify, Arrayify};
use FloatPHP\Classes\Html\Hook;
use FloatPHP\Classes\Http\Server;
use FloatPHP\Interfaces\Classes\RouterInterface;
use FloatPHP\Exceptions\Classes\RouterException;
/**
* Built-in HTTP router class.
* @see https://dannyvankooten.github.io/AltoRouter/
*/
class Router implements RouterInterface
{
/**
* @access public
*
* @var string BASE, Routes base path
* @var string REGEX, Routes compile pattern
* @var array TYPES, Routes matching types (regex)
*/
public const BASE = '';
public const REGEX = '`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`';
public const TYPES = [
'i' => '[0-9]++',
'a' => '[0-9A-Za-z]++',
'h' => '[0-9A-Fa-f]++',
'*' => '.+?',
'**' => '.++',
'' => '[^/\.]++'
];
/**
* @access protected
*
* @var array $routes
* @var string $base, Route base path
* @var array $types, Route types
* @var array $names, Named routes
*/
protected $routes = [];
protected $base;
protected $types = [];
protected $names = [];
/**
* @inheritdoc
*/
public function __construct(array $routes = [], string $base = self::BASE, array $types = self::TYPES)
{
$this->addRoutes($routes);
$this->setBase($base);
$this->addTypes($types);
}
/**
* @inheritdoc
*/
public function getRoutes() : array
{
return $this->routes;
}
/**
* @inheritdoc
*/
public function addRoutes(array $routes) : void
{
if ( !TypeCheck::isArray($routes) && !($routes instanceof \Traversable) ) {
throw new RouterException(
RouterException::notTraversable()
);
}
foreach ($routes as $route) {
if ( TypeCheck::isArray($route) && !empty($route) ) {
Hook::callUserFunctionArray([$this, 'map'], $route);
}
}
}
/**
* @inheritdoc
*/
public function setBase(string $base) : void
{
$this->base = $base;
}
/**
* @inheritdoc
*/
public function addTypes(array $types) : void
{
$this->types = Arrayify::merge($this->types, $types);
}
/**
* Get router base path.
*
* @access public
* @return string
*/
public function getBase() : string
{
return $this->base;
}
/**
* Get route types.
*
* @access public
* @return array
*/
public function getTypes() : array
{
return $this->types;
}
/**
* Get named routes.
*
* @access public
* @return array
*/
public function getNames() : array
{
return $this->names;
}
/**
* Clear all routes.
*
* @access public
* @return void
*/
public function clearRoutes() : void
{
$this->routes = [];
$this->names = [];
}
/**
* Check if a named route exists.
*
* @access public
* @param string $name
* @return bool
*/
public function hasRoute(string $name) : bool
{
return isset($this->names[$name]);
}
/**
* @inheritdoc
*/
public function map(string $method, string $route, $controller, ?string $name = null, $permission = null) : void
{
// Validate required parameters
if ( empty($method) || empty($route) ) {
throw new RouterException('Method and route cannot be empty');
}
$this->routes[] = [$method, $route, $controller, $name, $permission];
if ( $name ) {
if ( isset($this->names[$name]) ) {
throw new RouterException(
RouterException::redeclared($name)
);
}
$this->names[$name] = $route;
}
}
/**
* @inheritdoc
*/
public function generate(string $name, array $params = []) : string
{
// Validate input
if ( empty($name) ) {
throw new RouterException('Route name cannot be empty');
}
// Check if named route exists
if ( !isset($this->names[$name]) ) {
throw new RouterException(
RouterException::notExisting($name)
);
}
// Replace named parameters
$route = $this->names[$name];
// Prepend base path to route url again
$url = "{$this->base}{$route}";
if ( Stringify::matchAll(static::REGEX, $route, $matches, 2) ) {
foreach ($matches as $index => $match) {
list($block, $pre, $type, $param, $optional) = $match;
if ( $pre ) {
$block = substr($block, 1);
}
if ( isset($params[$param]) ) {
// Part is found, replace for param value
$url = Stringify::replace($block, $params[$param], $url);
} elseif ( $optional && $index !== 0 ) {
// Only strip preceding slash if it's not at the base
$url = Stringify::remove("{$pre}{$block}", $url);
} else {
// Strip matched block
$url = Stringify::remove($block, $url);
}
}
}
return $url;
}
/**
* @inheritdoc
*/
public function match(?string $url = null, ?string $method = null)
{
$params = [];
// Set request URL
if ( TypeCheck::isNull($url) ) {
$url = Server::get('request-uri') ?: '/';
}
// Set request method
if ( TypeCheck::isNull($method) ) {
$method = Server::get('request-method') ?: 'GET';
}
// Sanitize method (uppercase and validate)
$method = Stringify::uppercase($method);
// Strip base path from request URL
$url = substr($url, strlen($this->base));
// Strip query string (?a=b) from request URL
if ( ($strpos = strpos($url, '?')) !== false ) {
$url = substr($url, 0, $strpos);
}
// Get last request URL char
$last = $url ? $url[strlen($url) - 1] : '';
foreach ($this->routes as $handler) {
list($routeMethod, $route, $controller, $name, $permission) = $handler;
// Normalize route method for comparison
$routeMethod = Stringify::uppercase($routeMethod);
$routeMethodMatch = (stripos($routeMethod, $method) !== false) || $routeMethod === '*';
// Method did not match, continue to next route.
if ( !$routeMethodMatch ) {
continue;
}
if ( $route === '*' ) {
// * Wildcard (matches all)
$match = true;
} elseif ( isset($route[0]) && $route[0] === '@' ) {
// @ regex delimiter
$pattern = '`' . substr($route, 1) . '`u';
$match = Stringify::match($pattern, $url, $params);
} elseif ( ($position = strpos($route, '[')) === false ) {
// No params in URL, do string comparison
$match = strcmp($url, $route) === 0;
} else {
// Compare longest non-param string with URL
if (
(strncmp($url, $route, $position) !== 0)
&& ($last === '/' || $route[$position - 1] !== '/')
) {
continue;
}
$regex = $this->compile($route);
$match = Stringify::match($regex, $url, $params);
}
if ( $match ) {
if ( $params ) {
foreach ($params as $key => $value) {
if ( TypeCheck::isInt($key) ) {
unset($params[$key]);
}
}
}
return [
'target' => $controller,
'params' => $params,
'name' => $name,
'permission' => $permission
];
}
}
return false;
}
/**
* Compile route regex (Expensive).
*
* @access protected
* @param string $route
* @return string
*/
protected function compile(string $route) : string
{
if ( Stringify::matchAll(static::REGEX, $route, $matches, 2) ) {
foreach ($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
if ( isset($this->types[$type]) ) {
$type = $this->types[$type];
}
if ( $pre === '.' ) {
$pre = '\.';
}
$optional = $optional !== '' ? '?' : null;
// Legacy version of PCRE require the 'P' in (?P<named>)
$pattern = '(?:'
. ($pre !== '' ? $pre : null)
. '('
. ($param !== '' ? "?P<$param>" : null)
. $type
. ')'
. $optional
. ')'
. $optional;
$route = Stringify::replace($block, $pattern, $route);
}
}
return "`^{$route}$`u";
}
}