forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoRouterImproved.php
More file actions
592 lines (495 loc) · 17.9 KB
/
AutoRouterImproved.php
File metadata and controls
592 lines (495 loc) · 17.9 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
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Router;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\Router\Exceptions\MethodNotFoundException;
use Config\Routing;
use ReflectionClass;
use ReflectionException;
/**
* New Secure Router for Auto-Routing
*
* @see \CodeIgniter\Router\AutoRouterImprovedTest
*/
final class AutoRouterImproved implements AutoRouterInterface
{
/**
* Sub-directory that contains the requested controller class.
*/
private ?string $directory = null;
/**
* The name of the controller class.
*/
private string $controller;
/**
* The name of the method to use.
*/
private string $method;
/**
* An array of params to the controller method.
*
* @var list<string>
*/
private array $params = [];
/**
* Whether to translate dashes in URIs for controller/method to CamelCase.
* E.g., blog-controller -> BlogController
*/
private readonly bool $translateUriToCamelCase;
/**
* The namespace for controllers.
*/
private string $namespace;
/**
* Map of URI segments and namespaces.
*
* The key is the first URI segment. The value is the controller namespace.
* E.g.,
* [
* 'blog' => 'Acme\Blog\Controllers',
* ]
*
* @var array [ uri_segment => namespace ]
*/
private array $moduleRoutes;
/**
* The URI segments.
*
* @var list<string>
*/
private array $segments = [];
/**
* The position of the Controller in the URI segments.
* Null for the default controller.
*/
private ?int $controllerPos = null;
/**
* The position of the Method in the URI segments.
* Null for the default method.
*/
private ?int $methodPos = null;
/**
* The position of the first Parameter in the URI segments.
* Null for the no parameters.
*/
private ?int $paramPos = null;
/**
* The current URI
*/
private ?string $uri = null;
/**
* @param list<class-string> $protectedControllers
* @param string $defaultController Short classname
*/
public function __construct(
/**
* List of controllers in Defined Routes that should not be accessed via this Auto-Routing.
*/
private readonly array $protectedControllers,
string $namespace,
private readonly string $defaultController,
/**
* The name of the default method without HTTP verb prefix.
*/
private readonly string $defaultMethod,
/**
* Whether dashes in URI's should be converted
* to underscores when determining method names.
*/
private readonly bool $translateURIDashes,
) {
$this->namespace = rtrim($namespace, '\\');
$routingConfig = config(Routing::class);
$this->moduleRoutes = $routingConfig->moduleRoutes;
$this->translateUriToCamelCase = $routingConfig->translateUriToCamelCase;
// Set the default values
$this->controller = $this->defaultController;
}
private function createSegments(string $uri): array
{
$segments = explode('/', $uri);
$segments = array_filter($segments, static fn ($segment): bool => $segment !== '');
// numerically reindex the array, removing gaps
return array_values($segments);
}
/**
* Search for the first controller corresponding to the URI segment.
*
* If there is a controller corresponding to the first segment, the search
* ends there. The remaining segments are parameters to the controller.
*
* @return bool true if a controller class is found.
*/
private function searchFirstController(): bool
{
$segments = $this->segments;
$controller = '\\' . $this->namespace;
$controllerPos = -1;
while ($segments !== []) {
$segment = array_shift($segments);
$controllerPos++;
$class = $this->translateURI($segment);
// as soon as we encounter any segment that is not PSR-4 compliant, stop searching
if (! $this->isValidSegment($class)) {
return false;
}
$controller .= '\\' . $class;
if (class_exists($controller)) {
$this->controller = $controller;
$this->controllerPos = $controllerPos;
$this->checkUriForController($controller);
// The first item may be a method name.
$this->params = $segments;
if ($segments !== []) {
$this->paramPos = $this->controllerPos + 1;
}
return true;
}
}
return false;
}
/**
* Search for the last default controller corresponding to the URI segments.
*
* @return bool true if a controller class is found.
*/
private function searchLastDefaultController(): bool
{
$segments = $this->segments;
$segmentCount = count($this->segments);
$paramPos = null;
$params = [];
while ($segments !== []) {
if ($segmentCount > count($segments)) {
$paramPos = count($segments);
}
$namespaces = array_map(
$this->translateURI(...),
$segments,
);
$controller = '\\' . $this->namespace
. '\\' . implode('\\', $namespaces)
. '\\' . $this->defaultController;
if (class_exists($controller)) {
$this->controller = $controller;
$this->params = $params;
if ($params !== []) {
$this->paramPos = $paramPos;
}
return true;
}
// Prepend the last element in $segments to the beginning of $params.
array_unshift($params, array_pop($segments));
}
// Check for the default controller in Controllers directory.
$controller = '\\' . $this->namespace
. '\\' . $this->defaultController;
if (class_exists($controller)) {
$this->controller = $controller;
$this->params = $params;
if ($params !== []) {
$this->paramPos = 0;
}
return true;
}
return false;
}
/**
* Finds controller, method and params from the URI.
*
* @param string $httpVerb HTTP verb like `GET`,`POST`
*
* @return array [directory_name, controller_name, controller_method, params]
*/
public function getRoute(string $uri, string $httpVerb): array
{
$this->uri = $uri;
$httpVerb = strtolower($httpVerb);
// Reset Controller method params.
$this->params = [];
$defaultMethod = $httpVerb . ucfirst($this->defaultMethod);
$this->method = $defaultMethod;
$this->segments = $this->createSegments($uri);
// Check for Module Routes.
if (
$this->segments !== []
&& array_key_exists($this->segments[0], $this->moduleRoutes)
) {
$uriSegment = array_shift($this->segments);
$this->namespace = rtrim($this->moduleRoutes[$uriSegment], '\\');
}
if ($this->searchFirstController()) {
// Controller is found.
$baseControllerName = class_basename($this->controller);
// Prevent access to default controller path
if (
strtolower($baseControllerName) === strtolower($this->defaultController)
) {
throw new PageNotFoundException(
'Cannot access the default controller "' . $this->controller . '" with the controller name URI path.',
);
}
} elseif ($this->searchLastDefaultController()) {
// The default Controller is found.
$baseControllerName = class_basename($this->controller);
} else {
// No Controller is found.
throw new PageNotFoundException('No controller is found for: ' . $uri);
}
// The first item may be a method name.
/** @var list<string> $params */
$params = $this->params;
$methodParam = array_shift($params);
$method = '';
if ($methodParam !== null) {
$method = $httpVerb . $this->translateURI($methodParam);
$this->checkUriForMethod($method);
}
if ($methodParam !== null && method_exists($this->controller, $method)) {
// Method is found.
$this->method = $method;
$this->params = $params;
// Update the positions.
$this->methodPos = $this->paramPos;
if ($params === []) {
$this->paramPos = null;
}
if ($this->paramPos !== null) {
$this->paramPos++;
}
// Prevent access to default controller's method
if (strtolower($baseControllerName) === strtolower($this->defaultController)) {
throw new PageNotFoundException(
'Cannot access the default controller "' . $this->controller . '::' . $this->method . '"',
);
}
// Prevent access to default method path
if (strtolower($this->method) === strtolower($defaultMethod)) {
throw new PageNotFoundException(
'Cannot access the default method "' . $this->method . '" with the method name URI path.',
);
}
} elseif (method_exists($this->controller, $defaultMethod)) {
// The default method is found.
$this->method = $defaultMethod;
} else {
// No method is found.
throw PageNotFoundException::forControllerNotFound($this->controller, $method);
}
// Ensure the controller is not defined in routes.
$this->protectDefinedRoutes();
// Ensure the controller does not have _remap() method.
$this->checkRemap();
// Ensure the URI segments for the controller and method do not contain
// underscores when $translateURIDashes is true.
$this->checkUnderscore();
// Check parameter count
try {
$this->checkParameters();
} catch (MethodNotFoundException) {
throw PageNotFoundException::forControllerNotFound($this->controller, $this->method);
}
$this->setDirectory();
return [$this->directory, $this->controller, $this->method, $this->params];
}
/**
* @internal For test purpose only.
*
* @return array<string, int|null>
*/
public function getPos(): array
{
return [
'controller' => $this->controllerPos,
'method' => $this->methodPos,
'params' => $this->paramPos,
];
}
/**
* Get the directory path from the controller and set it to the property.
*
* @return void
*/
private function setDirectory()
{
$segments = explode('\\', trim($this->controller, '\\'));
// Remove short classname.
array_pop($segments);
$namespaces = implode('\\', $segments);
$dir = str_replace(
'\\',
'/',
ltrim(substr($namespaces, strlen($this->namespace)), '\\'),
);
if ($dir !== '') {
$this->directory = $dir . '/';
}
}
private function protectDefinedRoutes(): void
{
$controller = strtolower($this->controller);
foreach ($this->protectedControllers as $controllerInRoutes) {
$routeLowerCase = strtolower($controllerInRoutes);
if ($routeLowerCase === $controller) {
throw new PageNotFoundException(
'Cannot access the controller in Defined Routes. Controller: ' . $controllerInRoutes,
);
}
}
}
private function checkParameters(): void
{
try {
$refClass = new ReflectionClass($this->controller);
} catch (ReflectionException) {
throw PageNotFoundException::forControllerNotFound($this->controller, $this->method);
}
try {
$refMethod = $refClass->getMethod($this->method);
$refParams = $refMethod->getParameters();
} catch (ReflectionException) {
throw new MethodNotFoundException();
}
if (! $refMethod->isPublic()) {
throw new MethodNotFoundException();
}
if (count($refParams) < count($this->params)) {
throw new PageNotFoundException(
'The param count in the URI are greater than the controller method params.'
. ' Handler:' . $this->controller . '::' . $this->method
. ', URI:' . $this->uri,
);
}
}
private function checkRemap(): void
{
try {
$refClass = new ReflectionClass($this->controller);
$refClass->getMethod('_remap');
throw new PageNotFoundException(
'AutoRouterImproved does not support `_remap()` method.'
. ' Controller:' . $this->controller,
);
} catch (ReflectionException) {
// Do nothing.
}
}
private function checkUnderscore(): void
{
if ($this->translateURIDashes === false) {
return;
}
$paramPos = $this->paramPos ?? count($this->segments);
for ($i = 0; $i < $paramPos; $i++) {
if (str_contains($this->segments[$i], '_')) {
throw new PageNotFoundException(
'AutoRouterImproved prohibits access to the URI'
. ' containing underscores ("' . $this->segments[$i] . '")'
. ' when $translateURIDashes is enabled.'
. ' Please use the dash.'
. ' Handler:' . $this->controller . '::' . $this->method
. ', URI:' . $this->uri,
);
}
}
}
/**
* Check URI for controller for $translateUriToCamelCase
*
* @param string $classname Controller classname that is generated from URI.
* The case may be a bit incorrect.
*/
private function checkUriForController(string $classname): void
{
if ($this->translateUriToCamelCase === false) {
return;
}
if (! in_array(ltrim($classname, '\\'), get_declared_classes(), true)) {
throw new PageNotFoundException(
'"' . $classname . '" is not found.',
);
}
}
/**
* Check URI for method for $translateUriToCamelCase
*
* @param string $method Controller method name that is generated from URI.
* The case may be a bit incorrect.
*/
private function checkUriForMethod(string $method): void
{
if ($this->translateUriToCamelCase === false) {
return;
}
if (
// For example, if `getSomeMethod()` exists in the controller, only
// the URI `controller/some-method` should be accessible. But if a
// visitor navigates to the URI `controller/somemethod`, `getSomemethod()`
// will be checked, and `method_exists()` will return true because
// method names in PHP are case-insensitive.
method_exists($this->controller, $method)
// But we do not permit `controller/somemethod`, so check the exact
// method name.
&& ! in_array($method, get_class_methods($this->controller), true)
) {
throw new PageNotFoundException(
'"' . $this->controller . '::' . $method . '()" is not found.',
);
}
}
/**
* Returns true if the supplied $segment string represents a valid PSR-4 compliant namespace/directory segment
*
* regex comes from https://www.php.net/manual/en/language.variables.basics.php
*/
private function isValidSegment(string $segment): bool
{
return (bool) preg_match('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/', $segment);
}
/**
* Translates URI segment to CamelCase or replaces `-` with `_`.
*/
private function translateURI(string $segment): string
{
if ($this->translateUriToCamelCase) {
if (strtolower($segment) !== $segment) {
throw new PageNotFoundException(
'AutoRouterImproved prohibits access to the URI'
. ' containing uppercase letters ("' . $segment . '")'
. ' when $translateUriToCamelCase is enabled.'
. ' Please use the dash.'
. ' URI:' . $this->uri,
);
}
if (str_contains($segment, '--')) {
throw new PageNotFoundException(
'AutoRouterImproved prohibits access to the URI'
. ' containing double dash ("' . $segment . '")'
. ' when $translateUriToCamelCase is enabled.'
. ' Please use the single dash.'
. ' URI:' . $this->uri,
);
}
return str_replace(
' ',
'',
ucwords(
preg_replace('/[\-]+/', ' ', $segment),
),
);
}
$segment = ucfirst($segment);
if ($this->translateURIDashes) {
return str_replace('-', '_', $segment);
}
return $segment;
}
}