-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathRouter.php
More file actions
854 lines (738 loc) · 20.6 KB
/
Router.php
File metadata and controls
854 lines (738 loc) · 20.6 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
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
<?php
namespace Dingo\Api\Routing;
use Closure;
use Exception;
use RuntimeException;
use Dingo\Api\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Dingo\Api\Http\Response;
use Illuminate\Http\JsonResponse;
use Dingo\Api\Http\InternalRequest;
use Illuminate\Container\Container;
use Dingo\Api\Contract\Routing\Adapter;
use Dingo\Api\Contract\Debug\ExceptionHandler;
use Illuminate\Http\Response as IlluminateResponse;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
class Router
{
/**
* Routing adapter instance.
*
* @var \Dingo\Api\Contract\Routing\Adapter
*/
protected $adapter;
/**
* Accept parser instance.
*
* @var \Dingo\Api\Http\Parser\Accept
*/
protected $accept;
/**
* Exception handler instance.
*
* @var \Dingo\Api\Contract\Debug\ExceptionHandler
*/
protected $exception;
/**
* Application container instance.
*
* @var \Illuminate\Container\Container
*/
protected $container;
/**
* Group stack array.
*
* @var array
*/
protected $groupStack = [];
/**
* Indicates if the request is conditional.
*
* @var bool
*/
protected $conditionalRequest = true;
/**
* The current route being dispatched.
*
* @var \Dingo\Api\Routing\Route
*/
protected $currentRoute;
/**
* The number of routes dispatched.
*
* @var int
*/
protected $routesDispatched = 0;
/**
* The API domain.
*
* @var string
*/
protected $domain;
/**
* The API prefix.
*
* @var string
*/
protected $prefix;
/**
* Create a new router instance.
*
* @param \Dingo\Api\Contract\Routing\Adapter $adapter
* @param \Dingo\Api\Http\Parser\Accept $accept
* @param \Dingo\Api\Contract\Debug\ExceptionHandler $exception
* @param \Illuminate\Container\Container $container
* @param string $domain
* @param string $prefix
*
* @return void
*/
public function __construct(Adapter $adapter, ExceptionHandler $exception, Container $container, $domain, $prefix)
{
$this->adapter = $adapter;
$this->exception = $exception;
$this->container = $container;
$this->domain = $domain;
$this->prefix = $prefix;
}
/**
* An alias for calling the group method, allows a more fluent API
* for registering a new API version group with optional
* attributes and a required callback.
*
* This method can be called without the third parameter, however,
* the callback should always be the last paramter.
*
* @param string $version
* @param array|callable $second
* @param callable $third
*
* @return void
*/
public function version($version, $second, $third = null)
{
if (func_num_args() == 2) {
list($version, $callback, $attributes) = array_merge(func_get_args(), [[]]);
} else {
list($version, $attributes, $callback) = func_get_args();
}
$attributes = array_merge($attributes, ['version' => $version]);
$this->group($attributes, $callback);
}
/**
* Create a new route group.
*
* @param array $attributes
* @param callable $callback
*
* @return void
*/
public function group(array $attributes, $callback)
{
if (! isset($attributes['conditionalRequest'])) {
$attributes['conditionalRequest'] = $this->conditionalRequest;
}
$attributes = $this->mergeLastGroupAttributes($attributes);
if (! isset($attributes['version'])) {
throw new RuntimeException('A version is required for an API group definition.');
} else {
$attributes['version'] = (array) $attributes['version'];
}
if ((! isset($attributes['prefix']) || empty($attributes['prefix'])) && isset($this->prefix)) {
$attributes['prefix'] = $this->prefix;
}
if ((! isset($attributes['domain']) || empty($attributes['domain'])) && isset($this->domain)) {
$attributes['domain'] = $this->domain;
}
$this->groupStack[] = $attributes;
call_user_func($callback, $this);
array_pop($this->groupStack);
}
/**
* Create a new GET route.
*
* @param string $uri
* @param array|string|callable $action
*
* @return mixed
*/
public function get($uri, $action)
{
return $this->addRoute(['GET', 'HEAD'], $uri, $action);
}
/**
* Create a new POST route.
*
* @param string $uri
* @param array|string|callable $action
*
* @return mixed
*/
public function post($uri, $action)
{
return $this->addRoute('POST', $uri, $action);
}
/**
* Create a new PUT route.
*
* @param string $uri
* @param array|string|callable $action
*
* @return mixed
*/
public function put($uri, $action)
{
return $this->addRoute('PUT', $uri, $action);
}
/**
* Create a new PATCH route.
*
* @param string $uri
* @param array|string|callable $action
*
* @return mixed
*/
public function patch($uri, $action)
{
return $this->addRoute('PATCH', $uri, $action);
}
/**
* Create a new DELETE route.
*
* @param string $uri
* @param array|string|callable $action
*
* @return mixed
*/
public function delete($uri, $action)
{
return $this->addRoute('DELETE', $uri, $action);
}
/**
* Create a new OPTIONS route.
*
* @param string $uri
* @param array|string|callable $action
*
* @return mixed
*/
public function options($uri, $action)
{
return $this->addRoute('OPTIONS', $uri, $action);
}
/**
* Create a new route that responding to all verbs.
*
* @param string $uri
* @param array|string|callable $action
*
* @return mixed
*/
public function any($uri, $action)
{
$verbs = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'];
return $this->addRoute($verbs, $uri, $action);
}
/**
* Create a new route with the given verbs.
*
* @param array|string $methods
* @param string $uri
* @param array|string|callable $action
*
* @return mixed
*/
public function match($methods, $uri, $action)
{
return $this->addRoute(array_map('strtoupper', (array) $methods), $uri, $action);
}
/**
* Register an array of resources.
*
* @param array $resources
*
* @return void
*/
public function resources(array $resources)
{
foreach ($resources as $name => $resource) {
$options = [];
if (is_array($resource)) {
list($resource, $options) = $resource;
}
$this->resource($name, $resource, $options);
}
}
/**
* Register a resource controller.
*
* @param string $name
* @param string $controller
* @param array $options
*
* @return void
*/
public function resource($name, $controller, array $options = [])
{
if ($this->container->bound(ResourceRegistrar::class)) {
$registrar = $this->container->make(ResourceRegistrar::class);
} else {
$registrar = new ResourceRegistrar($this);
}
$registrar->register($name, $controller, $options);
}
/**
* Add a route to the routing adapter.
*
* @param string|array $methods
* @param string $uri
* @param string|array|callable $action
*
* @return mixed
*/
public function addRoute($methods, $uri, $action)
{
if (is_string($action)) {
$action = ['uses' => $action, 'controller' => $action];
} elseif ($action instanceof Closure) {
$action = [$action];
}
$action = $this->mergeLastGroupAttributes($action);
$action = $this->addControllerMiddlewareToRouteAction($action);
$uri = $uri === '/' ? $uri : '/'.trim($uri, '/');
if (! empty($action['prefix'])) {
$uri = '/'.ltrim(rtrim(trim($action['prefix'], '/').'/'.trim($uri, '/'), '/'), '/');
unset($action['prefix']);
}
$action['uri'] = $uri;
return $this->adapter->addRoute((array) $methods, $action['version'], $uri, $action);
}
/**
* Add the controller preparation middleware to the beginning of the routes middleware.
*
* @param array $action
*
* @return array
*/
protected function addControllerMiddlewareToRouteAction(array $action)
{
array_unshift($action['middleware'], 'api.controllers');
return $action;
}
/**
* Merge the last groups attributes.
*
* @param array $attributes
*
* @return array
*/
protected function mergeLastGroupAttributes(array $attributes)
{
if (empty($this->groupStack)) {
return $this->mergeGroup($attributes, []);
}
return $this->mergeGroup($attributes, end($this->groupStack));
}
/**
* Merge the given group attributes.
*
* @param array $new
* @param array $old
*
* @return array
*/
protected function mergeGroup(array $new, array $old)
{
$new['namespace'] = $this->formatNamespace($new, $old);
$new['prefix'] = $this->formatPrefix($new, $old);
foreach (['middleware', 'providers', 'scopes', 'before', 'after'] as $option) {
$new[$option] = $this->formatArrayBasedOption($option, $new);
}
if (isset($new['domain'])) {
unset($old['domain']);
}
if (isset($new['conditionalRequest'])) {
unset($old['conditionalRequest']);
}
if (isset($new['uses'])) {
$new['uses'] = $this->formatUses($new, $old);
}
$new['where'] = array_merge(Arr::get($old, 'where', []), Arr::get($new, 'where', []));
if (isset($old['as'])) {
$new['as'] = trim($old['as'].'.'.Arr::get($new, 'as', ''), '.');
}
return array_merge_recursive(array_except($old, ['namespace', 'prefix', 'where', 'as']), $new);
}
/**
* Format an array based option in a route action.
*
* @param string $option
* @param array $new
*
* @return array
*/
protected function formatArrayBasedOption($option, array $new)
{
$value = Arr::get($new, $option, []);
return is_string($value) ? explode('|', $value) : $value;
}
/**
* Format the uses key in a route action.
*
* @param array $new
* @param array $old
*
* @return string
*/
protected function formatUses(array $new, array $old)
{
if (isset($old['namespace']) && is_string($new['uses']) && strpos($new['uses'], '\\') !== 0) {
return $old['namespace'].'\\'.$new['uses'];
}
return $new['uses'];
}
/**
* Format the namespace for the new group attributes.
*
* @param array $new
* @param array $old
*
* @return string
*/
protected function formatNamespace(array $new, array $old)
{
if (isset($new['namespace']) && isset($old['namespace'])) {
return trim($old['namespace'], '\\').'\\'.trim($new['namespace'], '\\');
} elseif (isset($new['namespace'])) {
return trim($new['namespace'], '\\');
}
return Arr::get($old, 'namespace');
}
/**
* Format the prefix for the new group attributes.
*
* @param array $new
* @param array $old
*
* @return string
*/
protected function formatPrefix($new, $old)
{
if (isset($new['prefix'])) {
return trim(Arr::get($old, 'prefix'), '/').'/'.trim($new['prefix'], '/');
}
return Arr::get($old, 'prefix', '');
}
/**
* Dispatch a request via the adapter.
*
* @param \Dingo\Api\Http\Request $request
*
* @throws \Exception
*
* @return \Dingo\Api\Http\Response
*/
public function dispatch(Request $request)
{
$this->currentRoute = null;
$this->container->instance(Request::class, $request);
$this->routesDispatched++;
try {
$response = $this->adapter->dispatch($request, $request->version());
if (property_exists($response, 'exception') && $response->exception instanceof Exception) {
throw $response->exception;
}
} catch (Exception $exception) {
if ($request instanceof InternalRequest) {
throw $exception;
}
$this->exception->report($exception);
$response = $this->exception->handle($exception);
}
return $this->prepareResponse($response, $request, $request->format());
}
/**
* Prepare a response by transforming and formatting it correctly.
*
* @param mixed $response
* @param \Dingo\Api\Http\Request $request
* @param string $format
*
* @return \Dingo\Api\Http\Response
*/
protected function prepareResponse($response, Request $request, $format)
{
if (! ($response instanceof Response)) {
if ($response instanceof IlluminateResponse) {
$response = Response::makeFromExisting($response);
} elseif ($response instanceof JsonResponse) {
$response = Response::makeFromJson($response);
}
}
if ($response instanceof Response) {
// If we try and get a formatter that does not exist we'll let the exception
// handler deal with it. At worst we'll get a generic JSON response that
// a consumer can hopefully deal with. Ideally they won't be using
// an unsupported format.
try {
$response->getFormatter($format)->setResponse($response)->setRequest($request);
} catch (NotAcceptableHttpException $exception) {
return $this->exception->handle($exception);
}
$response = $response->morph($format);
}
if ($response->isSuccessful() && $this->requestIsConditional()) {
if (! $response->headers->has('ETag')) {
$response->setEtag(sha1($response->getContent()));
}
$response->isNotModified($request);
}
return $response;
}
/**
* Gather the middleware for the given route.
*
* @param mixed $route
*
* @return array
*/
public function gatherRouteMiddlewares($route)
{
return $this->adapter->gatherRouteMiddlewares($route);
}
/**
* Determine if the request is conditional.
*
* @return bool
*/
protected function requestIsConditional()
{
return $this->getCurrentRoute()->requestIsConditional();
}
/**
* Set the conditional request.
*
* @param bool $conditionalRequest
*
* @return void
*/
public function setConditionalRequest($conditionalRequest)
{
$this->conditionalRequest = $conditionalRequest;
}
/**
* Get the current request instance.
*
* @return \Dingo\Api\Http\Request
*/
public function getCurrentRequest()
{
return $this->container['request'];
}
/**
* Get the current route instance.
*
* @return \Dingo\Api\Routing\Route
*/
public function getCurrentRoute()
{
if (isset($this->currentRoute)) {
return $this->currentRoute;
} elseif (! $this->hasDispatchedRoutes() || ! $route = $this->container['request']->route()) {
return;
}
return $this->currentRoute = $this->createRoute($route);
}
/**
* Get the currently dispatched route instance.
*
* @return \Illuminate\Routing\Route
*/
public function current()
{
return $this->getCurrentRoute();
}
/**
* Create a new route instance from an adapter route.
*
* @param array|\Illuminate\Routing\Route $route
*
* @return \Dingo\Api\Routing\Route
*/
public function createRoute($route)
{
return new Route($this->adapter, $this->container, $this->container['request'], $route);
}
/**
* Set the current route instance.
*
* @param \Dingo\Api\Routing\Route $route
*
* @return void
*/
public function setCurrentRoute(Route $route)
{
$this->currentRoute = $route;
}
/**
* Determine if the router has a group stack.
*
* @return bool
*/
public function hasGroupStack()
{
return ! empty($this->groupStack);
}
/**
* Get the prefix from the last group on the stack.
*
* @return string
*/
public function getLastGroupPrefix()
{
if (empty($this->groupStack)) {
return '';
}
$group = end($this->groupStack);
return $group['prefix'];
}
/**
* Get all routes registered on the adapter.
*
* @param string $version
*
* @return mixed
*/
public function getRoutes($version = null)
{
$routes = $this->adapter->getIterableRoutes($version);
if (! is_null($version)) {
$routes = [$version => $routes];
}
$collections = [];
foreach ($routes as $key => $value) {
$collections[$key] = new RouteCollection($this->container['request']);
foreach ($value as $route) {
$route = $this->createRoute($route);
$collections[$key]->add($route);
}
}
return is_null($version) ? $collections : $collections[$version];
}
/**
* Get the raw adapter routes.
*
* @return array
*/
public function getAdapterRoutes()
{
return $this->adapter->getRoutes();
}
/**
* Set the raw adapter routes.
*
* @param array $routes
*
* @return void
*/
public function setAdapterRoutes(array $routes)
{
$this->adapter->setRoutes($routes);
$this->container->instance('api.routes', $this->getRoutes());
}
/**
* Get the number of routes dispatched.
*
* @return int
*/
public function getRoutesDispatched()
{
return $this->routesDispatched;
}
/**
* Determine if the router has dispatched any routes.
*
* @return bool
*/
public function hasDispatchedRoutes()
{
return $this->routesDispatched > 0;
}
/**
* Get the current route name.
*
* @return string|null
*/
public function currentRouteName()
{
return $this->current() ? $this->current()->getName() : null;
}
/**
* Alias for the "currentRouteNamed" method.
*
* @param mixed string
*
* @return bool
*/
public function is()
{
foreach (func_get_args() as $pattern) {
if (Str::is($pattern, $this->currentRouteName())) {
return true;
}
}
return false;
}
/**
* Determine if the current route matches a given name.
*
* @param string $name
*
* @return bool
*/
public function currentRouteNamed($name)
{
return $this->current() ? $this->current()->getName() == $name : false;
}
/**
* Get the current route action.
*
* @return string|null
*/
public function currentRouteAction()
{
if (! $route = $this->current()) {
return;
}
$action = $route->getAction();
return is_string($action['uses']) ? $action['uses'] : null;
}
/**
* Alias for the "currentRouteUses" method.
*
* @param mixed string
*
* @return bool
*/
public function uses()
{
foreach (func_get_args() as $pattern) {
if (Str::is($pattern, $this->currentRouteAction())) {
return true;
}
}
return false;
}
/**
* Determine if the current route action matches a given action.
*
* @param string $action
*
* @return bool
*/
public function currentRouteUses($action)
{
return $this->currentRouteAction() == $action;
}
}