-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRoute.hh
532 lines (446 loc) · 14.2 KB
/
Route.hh
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
<?hh // strict
/**
* @copyright 2010-2015, The Titon Project
* @license http://opensource.org/licenses/bsd-license.php
* @link http://titon.io
*/
namespace Titon\Route;
use Titon\Route\Exception\MissingPatternException;
use Titon\Route\Exception\NoMatchException;
use Titon\Route\Mixin\ConditionMixin;
use Titon\Route\Mixin\FilterMixin;
use Titon\Route\Mixin\MethodMixin;
use Titon\Route\Mixin\PatternMixin;
use Titon\Route\Mixin\SecureMixin;
use Titon\Utility\State\Server;
use Titon\Utility\Registry;
use \ReflectionFunctionAbstract;
use \ReflectionMethod;
use \Serializable;
/**
* Represents the skeleton for an individual route. A route is paired with a tokenized path that is matched and converted to a
* routeable URL. Routes support filters, patterns, conditional matching, and more.
*
* @package Titon\Route
*/
class Route implements Serializable {
use ConditionMixin, FilterMixin, MethodMixin, PatternMixin, SecureMixin;
/**
* Pre-defined regex patterns.
*/
const string ALPHA = '([a-z\_\-\.]+)';
const string ALNUM = '([a-z0-9\_\-\.]+)';
const string NUMERIC = '([0-9\.]+)';
const string WILDCARD = '([^\/]+)';
const string LOCALE = '([a-z]{2}(?:-[a-z]{2})?)';
/**
* The action to execute if this route is matched.
*
* @var \Titon\Route\Action
*/
protected Action $action;
/**
* The compiled regex pattern.
*
* @var string
*/
protected string $compiled = '';
/**
* Collection of route parameters.
*
* @var \Titon\Route\ParamMap
*/
protected ParamMap $params = Map {};
/**
* The path to match.
*
* @var string
*/
protected string $path = '';
/**
* A static route that contains no patterns.
*
* @var bool
*/
protected bool $static = false;
/**
* Custom defined tokens.
*
* @var \Titon\Route\TokenList
*/
protected TokenList $tokens = Vector {};
/**
* The corresponding URL when a match is found.
*
* @var string
*/
protected string $url = '';
/**
* Store the tokenized URL to match and the action to route to.
*
* @uses Titon\Route\Router
*
* @param string $path
* @param string $action
*/
public function __construct(string $path, string $action) {
$this->action = Router::parseAction($action);
$this->append($path);
}
/**
* Append onto the path. This must be done before compilation.
*
* @param string $path
* @return $this
*/
public function append(string $path): this {
$this->path .= '/' . trim($path, '/');
return $this;
}
/**
* Compile the given path into a detectable regex pattern.
*
* @return string
* @throws \Titon\Route\Exception\MissingPatternException
*/
public function compile(): string {
if ($this->isCompiled()) {
return $this->compiled;
}
$path = $this->getPath();
$compiled = str_replace(['/', '.'], ['\/', '\.'], $path);
$patterns = $this->getPatterns();
if (!$this->isStatic()) {
$tokens = [];
$matches = [];
// Match regex pattern tokens first
preg_match_all('/(\<)([^\<\>]+)(\>)/i', $path, $matches, PREG_SET_ORDER);
$tokens = array_merge($tokens, $matches);
// Then match regular tokens
preg_match_all('/(\{|\(|\[)([a-z0-9\?]+)(\}|\)|\])/i', $path, $matches, PREG_SET_ORDER);
$tokens = array_merge($tokens, $matches);
if ($tokens) {
foreach ($tokens as $match) {
$chunk = $match[0];
$open = array_key_exists(1, $match) ? $match[1] : ''; // opening brace
$token = array_key_exists(2, $match) ? $match[2] : ''; // token
$close = array_key_exists(3, $match) ? $match[3] : ''; // closing brace
$optional = false;
// Is the token optional
if (substr($token, -1) === '?') {
$optional = true;
$token = substr($token, 0, strlen($token) - 1);
}
// Pattern exists
if (strpos($token, ':') !== false) {
list($token, $pattern) = explode(':', $token, 2);
$patterns[$token] = $pattern;
$this->addPattern($token, $pattern);
}
if ($open === '{' && $close === '}') {
$pattern = self::ALNUM;
} else if ($open === '[' && $close === ']') {
$pattern = self::NUMERIC;
} else if ($open === '(' && $close === ')') {
$pattern = self::WILDCARD;
} else if ($open === '<' && $close === '>' && $patterns->contains($token)) {
$pattern = '(' . trim($patterns[$token], '()') . ')';
} else {
throw new MissingPatternException(sprintf('Unknown pattern for %s token', $token));
}
// Apply optional flag by altering chunk and pattern
if ($optional) {
$chunk = '\/' . $chunk;
$pattern = '(?:\/' . $pattern . ')?';
}
$compiled = str_replace($chunk, $pattern, $compiled);
$this->tokens[] = shape('token' => $token, 'optional' => $optional);
}
} else {
$this->setStatic(true);
}
}
// Append a check for a trailing slash
if ($path !== '/') {
$compiled .= '\/?';
}
// Save the compiled regex
return $this->compiled = $compiled;
}
/**
* Dispatch the current route to the defined action only if the route has been matched.
* The dispatcher will use the params gathered from the token list to pass as arguments to the action.
* Arguments will take into account default values defined on the method.
*
* @return mixed - The response of the action call
* @exception \Titon\Route\Exception\NoMatchException
*/
public function dispatch(): mixed {
if (!$this->isMatched()) {
throw new NoMatchException('Route cannot be dispatched unless it has been matched');
}
$action = $this->getAction();
$object = Registry::factory($action['class'], []);
$method = new ReflectionMethod($object, $action['action']);
return $method->invokeArgs($object, $this->getActionArguments());
}
/**
* Return the action to dispatch to.
*
* @return \Titon\Route\Action
*/
public function getAction(): Action {
return $this->action;
}
/**
* Return the type casted arguments for the defined action method.
*
* @return \Titon\Route\ArgumentList
*/
public function getActionArguments(): ArgumentList {
$action = $this->getAction();
$method = new ReflectionMethod($action['class'], $action['action']);
return $this->getArguments($method);
}
/**
* Return the custom path.
*
* @return string
*/
public function getPath(): string {
return $this->path;
}
/**
* Return a param from the matched route.
*
* @param string $key
* @return mixed
*/
public function getParam(string $key): mixed {
return $this->getParams()->get($key);
}
/**
* Return all params.
*
* @return \Titon\Route\ParamMap
*/
public function getParams(): ParamMap {
return $this->params;
}
/**
* Return the static configuration.
*
* @return bool
*/
public function getStatic(): bool {
return $this->static;
}
/**
* Return the compiled tokens.
*
* @return \Titon\Route\TokenList
*/
public function getTokens(): TokenList {
return $this->tokens;
}
/**
* Has the regex pattern been compiled?
*
* @return bool
*/
public function isCompiled(): bool {
return ($this->compiled !== '');
}
/**
* Does the URL match the current route?
*
* @param string $url
* @return bool
*/
public function isMatch(string $url): bool {
$matches = [];
// Compile the regex pattern
$this->compile();
// Match the route based on a set of conditions
if (!$this->isMethod()) {
return false;
} else if (!$this->isSecure()) {
return false;
} else if (!$this->isValid()) {
return false;
} else if ($this->getPath() === $url) {
$this->url = $url;
return true;
} else if (preg_match('~^' . $this->compile() . '$~i', $url, $matches)) {
$this->match($matches);
return true;
}
return false;
}
/**
* Return true if the route has been matched.
*
* @return bool
*/
public function isMatched(): bool {
return (bool) $this->url();
}
/**
* Validates the route matches the correct HTTP method.
*
* @return bool
*/
public function isMethod(): bool {
$methods = $this->getMethods();
if ($methods && !in_array(strtolower(Server::get('REQUEST_METHOD')), $methods, true)) {
return false;
}
return true;
}
/**
* Validates the route matches a secure connection.
*
* @return bool
*/
public function isSecure(): bool {
if ($this->getSecure() && !(Server::get('HTTPS') === 'on' || Server::get('SERVER_PORT') === '443')) {
return false; // Only validate if the secure flag is true
}
return true;
}
/**
* Is the route static (no regex patterns)?
*
* @return bool
*/
public function isStatic(): bool {
return (bool) $this->getStatic();
}
/**
* Validate the route is matchable by running through all defined conditions.
*
* @return bool
*/
public function isValid(): bool {
foreach ($this->getConditions() as $condition) {
if (!call_user_func($condition, $this)) {
return false;
}
}
return true;
}
/**
* Receive a list of matched values and apply it to the current route.
* These matches will equate to tokens, arguments, and other required values.
*
* @param array<string> $matches
* @return $this
*/
public function match(array<string> $matches): this {
$tokens = $this->getTokens();
$this->url = array_shift($matches);
if ($matches && $tokens) {
foreach ($tokens as $token) {
$this->params[$token['token']] = array_shift($matches);
}
}
return $this;
}
/**
* Prepend onto the path. This must be done before compilation.
*
* @param string $path
* @return $this
*/
public function prepend(string $path): this {
$this->path = '/' . trim($path, '/') . rtrim($this->path, '/');
return $this;
}
/**
* Serialize the compiled route for increasing performance when caching mapped routes.
*/
public function serialize(): string {
return serialize(Map {
'action' => $this->getAction(),
'compiled' => $this->compile(),
'filters' => $this->getFilters(),
'methods' => $this->getMethods(),
'patterns' => $this->getPatterns(),
'path' => $this->getPath(),
'secure' => $this->getSecure(),
'static' => $this->getStatic(),
'tokens' => $this->getTokens()
});
}
/**
* Set the action to dispatch to.
*
* @param \Titon\Route\Action $action
* @return $this
*/
public function setAction(Action $action): this {
$this->action = $action;
return $this;
}
/**
* Set the static flag.
*
* @param bool $static
* @return $this
*/
public function setStatic(bool $static): this {
$this->static = $static;
return $this;
}
/**
* Unserialize the route and set the internal values.
*
* @param mixed $data
*/
public function unserialize(/* HH_FIXME[4032]: no type hint */ $data): void {
$data = unserialize($data);
$this->path = $data['path'];
$this->action = $data['action'];
$this->tokens = $data['tokens'];
$this->compiled = $data['compiled'];
$this->setFilters($data['filters']);
$this->setMethods($data['methods']);
$this->setPatterns($data['patterns']);
$this->setSecure($data['secure']);
$this->setStatic($data['static']);
}
/**
* Return the currently matched full URL.
*
* @return string
*/
public function url(): string {
return $this->url;
}
/**
* Gather a list of arguments to pass to the dispatcher based on the tokens and params from the route.
* Furthermore, loop through and set any default values using reflection, and type cast appropriately.
*
* @param \ReflectionFunctionAbstract $method
* @return \Titon\Route\ArgumentList
*/
protected function getArguments(ReflectionFunctionAbstract $method): ArgumentList {
$tokens = $this->getTokens();
$args = $this->getParams()->values()->toArray();
foreach ($method->getParameters() as $i => $param) {
if (!$tokens->containsKey($i)) {
continue;
}
if ($tokens[$i]['optional'] && (!array_key_exists($i, $args) || $args[$i] === '' || $args[$i] === null)) {
$args[$i] = $param->getDefaultValue();
}
// Type cast the values to match the argument type hint
switch ($param->getTypehintText()) {
case 'HH\string': $args[$i] = (string) $args[$i]; break;
case 'HH\bool': $args[$i] = (bool) $args[$i]; break;
case 'HH\int': $args[$i] = (int) $args[$i]; break;
}
}
return $args;
}
}