-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
RouteCollection.php
1844 lines (1580 loc) · 57 KB
/
RouteCollection.php
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?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 Closure;
use CodeIgniter\Autoloader\FileLocatorInterface;
use CodeIgniter\HTTP\Method;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Router\Exceptions\RouterException;
use Config\App;
use Config\Modules;
use Config\Routing;
use InvalidArgumentException;
/**
* @todo Implement nested resource routing (See CakePHP)
* @see \CodeIgniter\Router\RouteCollectionTest
*/
class RouteCollection implements RouteCollectionInterface
{
/**
* The namespace to be added to any Controllers.
* Defaults to the global namespaces (\).
*
* This must have a trailing backslash (\).
*
* @var string
*/
protected $defaultNamespace = '\\';
/**
* The name of the default controller to use
* when no other controller is specified.
*
* Not used here. Pass-thru value for Router class.
*
* @var string
*/
protected $defaultController = 'Home';
/**
* The name of the default method to use
* when no other method has been specified.
*
* Not used here. Pass-thru value for Router class.
*
* @var string
*/
protected $defaultMethod = 'index';
/**
* The placeholder used when routing 'resources'
* when no other placeholder has been specified.
*
* @var string
*/
protected $defaultPlaceholder = 'any';
/**
* Whether to convert dashes to underscores in URI.
*
* Not used here. Pass-thru value for Router class.
*
* @var bool
*/
protected $translateURIDashes = false;
/**
* Whether to match URI against Controllers
* when it doesn't match defined routes.
*
* Not used here. Pass-thru value for Router class.
*
* @var bool
*/
protected $autoRoute = false;
/**
* A callable that will be shown
* when the route cannot be matched.
*
* @var (Closure(string): (ResponseInterface|string|void))|string
*/
protected $override404;
/**
* An array of files that would contain route definitions.
*/
protected array $routeFiles = [];
/**
* Defined placeholders that can be used
* within the
*
* @var array<string, string>
*/
protected $placeholders = [
'any' => '.*',
'segment' => '[^/]+',
'alphanum' => '[a-zA-Z0-9]+',
'num' => '[0-9]+',
'alpha' => '[a-zA-Z]+',
'hash' => '[^/]+',
];
/**
* An array of all routes and their mappings.
*
* @var array
*
* [
* verb => [
* routeKey(regex) => [
* 'name' => routeName
* 'handler' => handler,
* 'from' => from,
* ],
* ],
* // redirect route
* '*' => [
* routeKey(regex)(from) => [
* 'name' => routeName
* 'handler' => [routeKey(regex)(to) => handler],
* 'from' => from,
* 'redirect' => statusCode,
* ],
* ],
* ]
*/
protected $routes = [
'*' => [],
Method::OPTIONS => [],
Method::GET => [],
Method::HEAD => [],
Method::POST => [],
Method::PATCH => [],
Method::PUT => [],
Method::DELETE => [],
Method::TRACE => [],
Method::CONNECT => [],
'CLI' => [],
];
/**
* Array of routes names
*
* @var array
*
* [
* verb => [
* routeName => routeKey(regex)
* ],
* ]
*/
protected $routesNames = [
'*' => [],
Method::OPTIONS => [],
Method::GET => [],
Method::HEAD => [],
Method::POST => [],
Method::PATCH => [],
Method::PUT => [],
Method::DELETE => [],
Method::TRACE => [],
Method::CONNECT => [],
'CLI' => [],
];
/**
* Array of routes options
*
* @var array
*
* [
* verb => [
* routeKey(regex) => [
* key => value,
* ]
* ],
* ]
*/
protected $routesOptions = [];
/**
* The current method that the script is being called by.
*
* @var string HTTP verb like `GET`,`POST` or `*` or `CLI`
*/
protected $HTTPVerb = '*';
/**
* The default list of HTTP methods (and CLI for command line usage)
* that is allowed if no other method is provided.
*
* @var list<string>
*/
public $defaultHTTPMethods = Router::HTTP_METHODS;
/**
* The name of the current group, if any.
*
* @var string|null
*/
protected $group;
/**
* The current subdomain.
*
* @var string|null
*/
protected $currentSubdomain;
/**
* Stores copy of current options being
* applied during creation.
*
* @var array|null
*/
protected $currentOptions;
/**
* A little performance booster.
*
* @var bool
*/
protected $didDiscover = false;
/**
* Handle to the file locator to use.
*
* @var FileLocatorInterface
*/
protected $fileLocator;
/**
* Handle to the modules config.
*
* @var Modules
*/
protected $moduleConfig;
/**
* Flag for sorting routes by priority.
*
* @var bool
*/
protected $prioritize = false;
/**
* Route priority detection flag.
*
* @var bool
*/
protected $prioritizeDetected = false;
/**
* The current hostname from $_SERVER['HTTP_HOST']
*/
private ?string $httpHost = null;
/**
* Flag to limit or not the routes with {locale} placeholder to App::$supportedLocales
*/
protected bool $useSupportedLocalesOnly = false;
/**
* Constructor
*/
public function __construct(FileLocatorInterface $locator, Modules $moduleConfig, Routing $routing)
{
$this->fileLocator = $locator;
$this->moduleConfig = $moduleConfig;
$this->httpHost = service('request')->getServer('HTTP_HOST');
// Setup based on config file. Let routes file override.
$this->defaultNamespace = rtrim($routing->defaultNamespace, '\\') . '\\';
$this->defaultController = $routing->defaultController;
$this->defaultMethod = $routing->defaultMethod;
$this->translateURIDashes = $routing->translateURIDashes;
$this->override404 = $routing->override404;
$this->autoRoute = $routing->autoRoute;
$this->routeFiles = $routing->routeFiles;
$this->prioritize = $routing->prioritize;
// Normalize the path string in routeFiles array.
foreach ($this->routeFiles as $routeKey => $routesFile) {
$realpath = realpath($routesFile);
$this->routeFiles[$routeKey] = ($realpath === false) ? $routesFile : $realpath;
}
}
/**
* Loads main routes file and discover routes.
*
* Loads only once unless reset.
*
* @return $this
*/
public function loadRoutes(string $routesFile = APPPATH . 'Config/Routes.php')
{
if ($this->didDiscover) {
return $this;
}
// Normalize the path string in routesFile
$realpath = realpath($routesFile);
$routesFile = ($realpath === false) ? $routesFile : $realpath;
// Include the passed in routesFile if it doesn't exist.
// Only keeping that around for BC purposes for now.
$routeFiles = $this->routeFiles;
if (! in_array($routesFile, $routeFiles, true)) {
$routeFiles[] = $routesFile;
}
// We need this var in local scope
// so route files can access it.
$routes = $this;
foreach ($routeFiles as $routesFile) {
if (! is_file($routesFile)) {
log_message('warning', sprintf('Routes file not found: "%s"', $routesFile));
continue;
}
require $routesFile;
}
$this->discoverRoutes();
return $this;
}
/**
* Will attempt to discover any additional routes, either through
* the local PSR4 namespaces, or through selected Composer packages.
*
* @return void
*/
protected function discoverRoutes()
{
if ($this->didDiscover) {
return;
}
// We need this var in local scope
// so route files can access it.
$routes = $this;
if ($this->moduleConfig->shouldDiscover('routes')) {
$files = $this->fileLocator->search('Config/Routes.php');
foreach ($files as $file) {
// Don't include our main file again...
if (in_array($file, $this->routeFiles, true)) {
continue;
}
include $file;
}
}
$this->didDiscover = true;
}
/**
* Registers a new constraint with the system. Constraints are used
* by the routes as placeholders for regular expressions to make defining
* the routes more human-friendly.
*
* You can pass an associative array as $placeholder, and have
* multiple placeholders added at once.
*
* @param array|string $placeholder
*/
public function addPlaceholder($placeholder, ?string $pattern = null): RouteCollectionInterface
{
if (! is_array($placeholder)) {
$placeholder = [$placeholder => $pattern];
}
$this->placeholders = array_merge($this->placeholders, $placeholder);
return $this;
}
/**
* For `spark routes`
*
* @return array<string, string>
*
* @internal
*/
public function getPlaceholders(): array
{
return $this->placeholders;
}
/**
* Sets the default namespace to use for Controllers when no other
* namespace has been specified.
*/
public function setDefaultNamespace(string $value): RouteCollectionInterface
{
$this->defaultNamespace = esc(strip_tags($value));
$this->defaultNamespace = rtrim($this->defaultNamespace, '\\') . '\\';
return $this;
}
/**
* Sets the default controller to use when no other controller has been
* specified.
*/
public function setDefaultController(string $value): RouteCollectionInterface
{
$this->defaultController = esc(strip_tags($value));
return $this;
}
/**
* Sets the default method to call on the controller when no other
* method has been set in the route.
*/
public function setDefaultMethod(string $value): RouteCollectionInterface
{
$this->defaultMethod = esc(strip_tags($value));
return $this;
}
/**
* Tells the system whether to convert dashes in URI strings into
* underscores. In some search engines, including Google, dashes
* create more meaning and make it easier for the search engine to
* find words and meaning in the URI for better SEO. But it
* doesn't work well with PHP method names....
*/
public function setTranslateURIDashes(bool $value): RouteCollectionInterface
{
$this->translateURIDashes = $value;
return $this;
}
/**
* If TRUE, the system will attempt to match the URI against
* Controllers by matching each segment against folders/files
* in APPPATH/Controllers, when a match wasn't found against
* defined routes.
*
* If FALSE, will stop searching and do NO automatic routing.
*/
public function setAutoRoute(bool $value): RouteCollectionInterface
{
$this->autoRoute = $value;
return $this;
}
/**
* Sets the class/method that should be called if routing doesn't
* find a match. It can be either a closure or the controller/method
* name exactly like a route is defined: Users::index
*
* This setting is passed to the Router class and handled there.
*
* @param callable|string|null $callable
*/
public function set404Override($callable = null): RouteCollectionInterface
{
$this->override404 = $callable;
return $this;
}
/**
* Returns the 404 Override setting, which can be null, a closure
* or the controller/string.
*
* @return (Closure(string): (ResponseInterface|string|void))|string|null
*/
public function get404Override()
{
return $this->override404;
}
/**
* Sets the default constraint to be used in the system. Typically
* for use with the 'resource' method.
*/
public function setDefaultConstraint(string $placeholder): RouteCollectionInterface
{
if (array_key_exists($placeholder, $this->placeholders)) {
$this->defaultPlaceholder = $placeholder;
}
return $this;
}
/**
* Returns the name of the default controller. With Namespace.
*/
public function getDefaultController(): string
{
return $this->defaultController;
}
/**
* Returns the name of the default method to use within the controller.
*/
public function getDefaultMethod(): string
{
return $this->defaultMethod;
}
/**
* Returns the default namespace as set in the Routes config file.
*/
public function getDefaultNamespace(): string
{
return $this->defaultNamespace;
}
/**
* Returns the current value of the translateURIDashes setting.
*/
public function shouldTranslateURIDashes(): bool
{
return $this->translateURIDashes;
}
/**
* Returns the flag that tells whether to autoRoute URI against Controllers.
*/
public function shouldAutoRoute(): bool
{
return $this->autoRoute;
}
/**
* Returns the raw array of available routes.
*
* @param non-empty-string|null $verb HTTP verb like `GET`,`POST` or `*` or `CLI`.
* @param bool $includeWildcard Whether to include '*' routes.
*/
public function getRoutes(?string $verb = null, bool $includeWildcard = true): array
{
if ($verb === null || $verb === '') {
$verb = $this->getHTTPVerb();
}
// Since this is the entry point for the Router,
// take a moment to do any route discovery
// we might need to do.
$this->discoverRoutes();
$routes = [];
if (isset($this->routes[$verb])) {
// Keep current verb's routes at the beginning, so they're matched
// before any of the generic, "add" routes.
$collection = $includeWildcard ? $this->routes[$verb] + ($this->routes['*'] ?? []) : $this->routes[$verb];
foreach ($collection as $routeKey => $r) {
$routes[$routeKey] = $r['handler'];
}
}
// sorting routes by priority
if ($this->prioritizeDetected && $this->prioritize && $routes !== []) {
$order = [];
foreach ($routes as $key => $value) {
$key = $key === '/' ? $key : ltrim($key, '/ ');
$priority = $this->getRoutesOptions($key, $verb)['priority'] ?? 0;
$order[$priority][$key] = $value;
}
ksort($order);
$routes = array_merge(...$order);
}
return $routes;
}
/**
* Returns one or all routes options
*
* @param string|null $verb HTTP verb like `GET`,`POST` or `*` or `CLI`.
*
* @return array<string, int|string> [key => value]
*/
public function getRoutesOptions(?string $from = null, ?string $verb = null): array
{
$options = $this->loadRoutesOptions($verb);
return $from ? $options[$from] ?? [] : $options;
}
/**
* Returns the current HTTP Verb being used.
*/
public function getHTTPVerb(): string
{
return $this->HTTPVerb;
}
/**
* Sets the current HTTP verb.
* Used primarily for testing.
*
* @param string $verb HTTP verb
*
* @return $this
*/
public function setHTTPVerb(string $verb)
{
if ($verb !== '*' && $verb === strtolower($verb)) {
@trigger_error(
'Passing lowercase HTTP method "' . $verb . '" is deprecated.'
. ' Use uppercase HTTP method like "' . strtoupper($verb) . '".',
E_USER_DEPRECATED
);
}
/**
* @deprecated 4.5.0
* @TODO Remove strtoupper() in the future.
*/
$this->HTTPVerb = strtoupper($verb);
return $this;
}
/**
* A shortcut method to add a number of routes at a single time.
* It does not allow any options to be set on the route, or to
* define the method used.
*/
public function map(array $routes = [], ?array $options = null): RouteCollectionInterface
{
foreach ($routes as $from => $to) {
$this->add($from, $to, $options);
}
return $this;
}
/**
* Adds a single route to the collection.
*
* Example:
* $routes->add('news', 'Posts::index');
*
* @param array|(Closure(mixed...): (ResponseInterface|string|void))|string $to
*/
public function add(string $from, $to, ?array $options = null): RouteCollectionInterface
{
$this->create('*', $from, $to, $options);
return $this;
}
/**
* Adds a temporary redirect from one route to another. Used for
* redirecting traffic from old, non-existing routes to the new
* moved routes.
*
* @param string $from The pattern to match against
* @param string $to Either a route name or a URI to redirect to
* @param int $status The HTTP status code that should be returned with this redirect
*
* @return RouteCollection
*/
public function addRedirect(string $from, string $to, int $status = 302)
{
// Use the named route's pattern if this is a named route.
if (array_key_exists($to, $this->routesNames['*'])) {
$routeName = $to;
$routeKey = $this->routesNames['*'][$routeName];
$redirectTo = [$routeKey => $this->routes['*'][$routeKey]['handler']];
} elseif (array_key_exists($to, $this->routesNames[Method::GET])) {
$routeName = $to;
$routeKey = $this->routesNames[Method::GET][$routeName];
$redirectTo = [$routeKey => $this->routes[Method::GET][$routeKey]['handler']];
} else {
// The named route is not found.
$redirectTo = $to;
}
$this->create('*', $from, $redirectTo, ['redirect' => $status]);
return $this;
}
/**
* Determines if the route is a redirecting route.
*
* @param string $routeKey routeKey or route name
*/
public function isRedirect(string $routeKey): bool
{
if (isset($this->routes['*'][$routeKey]['redirect'])) {
return true;
}
// This logic is not used. Should be deprecated?
$routeName = $this->routes['*'][$routeKey]['name'] ?? null;
if ($routeName === $routeKey) {
$routeKey = $this->routesNames['*'][$routeName];
return isset($this->routes['*'][$routeKey]['redirect']);
}
return false;
}
/**
* Grabs the HTTP status code from a redirecting Route.
*
* @param string $routeKey routeKey or route name
*/
public function getRedirectCode(string $routeKey): int
{
if (isset($this->routes['*'][$routeKey]['redirect'])) {
return $this->routes['*'][$routeKey]['redirect'];
}
// This logic is not used. Should be deprecated?
$routeName = $this->routes['*'][$routeKey]['name'] ?? null;
if ($routeName === $routeKey) {
$routeKey = $this->routesNames['*'][$routeName];
return $this->routes['*'][$routeKey]['redirect'];
}
return 0;
}
/**
* Group a series of routes under a single URL segment. This is handy
* for grouping items into an admin area, like:
*
* Example:
* // Creates route: admin/users
* $route->group('admin', function() {
* $route->resource('users');
* });
*
* @param string $name The name to group/prefix the routes with.
* @param array|callable ...$params
*
* @return void
*/
public function group(string $name, ...$params)
{
$oldGroup = $this->group;
$oldOptions = $this->currentOptions;
// To register a route, we'll set a flag so that our router
// will see the group name.
// If the group name is empty, we go on using the previously built group name.
$this->group = $name !== '' ? trim($oldGroup . '/' . $name, '/') : $oldGroup;
$callback = array_pop($params);
if ($params && is_array($params[0])) {
$options = array_shift($params);
if (isset($options['filter'])) {
// Merge filters.
$currentFilter = (array) ($this->currentOptions['filter'] ?? []);
$options['filter'] = array_merge($currentFilter, (array) $options['filter']);
}
// Merge options other than filters.
$this->currentOptions = array_merge(
$this->currentOptions ?? [],
$options
);
}
if (is_callable($callback)) {
$callback($this);
}
$this->group = $oldGroup;
$this->currentOptions = $oldOptions;
}
/*
* --------------------------------------------------------------------
* HTTP Verb-based routing
* --------------------------------------------------------------------
* Routing works here because, as the routes Config file is read in,
* the various HTTP verb-based routes will only be added to the in-memory
* routes if it is a call that should respond to that verb.
*
* The options array is typically used to pass in an 'as' or var, but may
* be expanded in the future. See the docblock for 'add' method above for
* current list of globally available options.
*/
/**
* Creates a collections of HTTP-verb based routes for a controller.
*
* Possible Options:
* 'controller' - Customize the name of the controller used in the 'to' route
* 'placeholder' - The regex used by the Router. Defaults to '(:any)'
* 'websafe' - - '1' if only GET and POST HTTP verbs are supported
*
* Example:
*
* $route->resource('photos');
*
* // Generates the following routes:
* HTTP Verb | Path | Action | Used for...
* ----------+-------------+---------------+-----------------
* GET /photos index an array of photo objects
* GET /photos/new new an empty photo object, with default properties
* GET /photos/{id}/edit edit a specific photo object, editable properties
* GET /photos/{id} show a specific photo object, all properties
* POST /photos create a new photo object, to add to the resource
* DELETE /photos/{id} delete deletes the specified photo object
* PUT/PATCH /photos/{id} update replacement properties for existing photo
*
* If 'websafe' option is present, the following paths are also available:
*
* POST /photos/{id}/delete delete
* POST /photos/{id} update
*
* @param string $name The name of the resource/controller to route to.
* @param array|null $options A list of possible ways to customize the routing.
*/
public function resource(string $name, ?array $options = null): RouteCollectionInterface
{
// In order to allow customization of the route the
// resources are sent to, we need to have a new name
// to store the values in.
$newName = implode('\\', array_map(ucfirst(...), explode('/', $name)));
// If a new controller is specified, then we replace the
// $name value with the name of the new controller.
if (isset($options['controller'])) {
$newName = ucfirst(esc(strip_tags($options['controller'])));
}
// In order to allow customization of allowed id values
// we need someplace to store them.
$id = $options['placeholder'] ?? $this->placeholders[$this->defaultPlaceholder] ?? '(:segment)';
// Make sure we capture back-references
$id = '(' . trim($id, '()') . ')';
$methods = isset($options['only']) ? (is_string($options['only']) ? explode(',', $options['only']) : $options['only']) : ['index', 'show', 'create', 'update', 'delete', 'new', 'edit'];
if (isset($options['except'])) {
$options['except'] = is_array($options['except']) ? $options['except'] : explode(',', $options['except']);
foreach ($methods as $i => $method) {
if (in_array($method, $options['except'], true)) {
unset($methods[$i]);
}
}
}
if (in_array('index', $methods, true)) {
$this->get($name, $newName . '::index', $options);
}
if (in_array('new', $methods, true)) {
$this->get($name . '/new', $newName . '::new', $options);
}
if (in_array('edit', $methods, true)) {
$this->get($name . '/' . $id . '/edit', $newName . '::edit/$1', $options);
}
if (in_array('show', $methods, true)) {
$this->get($name . '/' . $id, $newName . '::show/$1', $options);
}
if (in_array('create', $methods, true)) {
$this->post($name, $newName . '::create', $options);
}
if (in_array('update', $methods, true)) {
$this->put($name . '/' . $id, $newName . '::update/$1', $options);
$this->patch($name . '/' . $id, $newName . '::update/$1', $options);
}
if (in_array('delete', $methods, true)) {
$this->delete($name . '/' . $id, $newName . '::delete/$1', $options);
}
// Web Safe? delete needs checking before update because of method name
if (isset($options['websafe'])) {
if (in_array('delete', $methods, true)) {
$this->post($name . '/' . $id . '/delete', $newName . '::delete/$1', $options);
}
if (in_array('update', $methods, true)) {
$this->post($name . '/' . $id, $newName . '::update/$1', $options);
}
}
return $this;
}
/**
* Creates a collections of HTTP-verb based routes for a presenter controller.
*
* Possible Options:
* 'controller' - Customize the name of the controller used in the 'to' route
* 'placeholder' - The regex used by the Router. Defaults to '(:any)'
*
* Example:
*
* $route->presenter('photos');
*
* // Generates the following routes:
* HTTP Verb | Path | Action | Used for...
* ----------+-------------+---------------+-----------------
* GET /photos index showing all array of photo objects
* GET /photos/show/{id} show showing a specific photo object, all properties
* GET /photos/new new showing a form for an empty photo object, with default properties
* POST /photos/create create processing the form for a new photo
* GET /photos/edit/{id} edit show an editing form for a specific photo object, editable properties
* POST /photos/update/{id} update process the editing form data
* GET /photos/remove/{id} remove show a form to confirm deletion of a specific photo object
* POST /photos/delete/{id} delete deleting the specified photo object
*
* @param string $name The name of the controller to route to.
* @param array|null $options A list of possible ways to customize the routing.
*/
public function presenter(string $name, ?array $options = null): RouteCollectionInterface
{
// In order to allow customization of the route the
// resources are sent to, we need to have a new name
// to store the values in.
$newName = implode('\\', array_map(ucfirst(...), explode('/', $name)));
// If a new controller is specified, then we replace the
// $name value with the name of the new controller.
if (isset($options['controller'])) {
$newName = ucfirst(esc(strip_tags($options['controller'])));
}
// In order to allow customization of allowed id values
// we need someplace to store them.
$id = $options['placeholder'] ?? $this->placeholders[$this->defaultPlaceholder] ?? '(:segment)';
// Make sure we capture back-references
$id = '(' . trim($id, '()') . ')';
$methods = isset($options['only']) ? (is_string($options['only']) ? explode(',', $options['only']) : $options['only']) : ['index', 'show', 'new', 'create', 'edit', 'update', 'remove', 'delete'];
if (isset($options['except'])) {
$options['except'] = is_array($options['except']) ? $options['except'] : explode(',', $options['except']);
foreach ($methods as $i => $method) {
if (in_array($method, $options['except'], true)) {
unset($methods[$i]);
}
}
}
if (in_array('index', $methods, true)) {
$this->get($name, $newName . '::index', $options);
}
if (in_array('show', $methods, true)) {
$this->get($name . '/show/' . $id, $newName . '::show/$1', $options);
}
if (in_array('new', $methods, true)) {
$this->get($name . '/new', $newName . '::new', $options);
}
if (in_array('create', $methods, true)) {
$this->post($name . '/create', $newName . '::create', $options);
}
if (in_array('edit', $methods, true)) {
$this->get($name . '/edit/' . $id, $newName . '::edit/$1', $options);
}
if (in_array('update', $methods, true)) {
$this->post($name . '/update/' . $id, $newName . '::update/$1', $options);
}
if (in_array('remove', $methods, true)) {
$this->get($name . '/remove/' . $id, $newName . '::remove/$1', $options);
}
if (in_array('delete', $methods, true)) {
$this->post($name . '/delete/' . $id, $newName . '::delete/$1', $options);
}
if (in_array('show', $methods, true)) {