Repository navigation
Expand file tree
/
Copy pathRouter.php
More file actions
495 lines (425 loc) · 12.8 KB
/
Copy pathRouter.php
File metadata and controls
495 lines (425 loc) · 12.8 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
<?php
namespace Dingo\Api\Routing;
use Exception;
use Dingo\Api\Config;
use BadMethodCallException;
use Illuminate\Http\Request;
use Illuminate\Events\Dispatcher;
use Dingo\Api\Http\ResponseBuilder;
use Dingo\Api\Http\InternalRequest;
use Illuminate\Container\Container;
use Dingo\Api\Http\Response as ApiResponse;
use Illuminate\Routing\Route as IlluminateRoute;
use Illuminate\Routing\Router as IlluminateRouter;
use Illuminate\Http\Response as IlluminateResponse;
use Dingo\Api\Exception\InvalidAcceptHeaderException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
class Router extends IlluminateRouter
{
/**
* API config instance.
*
* @var \Dingo\Api\Config
*/
protected $config;
/**
* API version collection instance.
*
* @var array
*/
protected $api;
/**
* Current API version.
*
* @var string
*/
protected $currentVersion;
/**
* Current API format.
*
* @var string
*/
protected $currentFormat;
/**
* Array of requests targetting the API.
*
* @var array
*/
protected $apiRequests = [];
/**
* Indicates if the request is a conditional request.
*
* @var bool
*/
protected $conditionalRequest;
/**
* Indicates if the request is in strict mode.
*
* @var bool
*/
protected $strict;
/**
* Name of the authentication filter.
*
* @var string
*/
const API_FILTER_AUTH = 'api.auth';
/**
* Name of the throttling filter.
*
* @var string
*/
const API_FILTER_THROTTLE = 'api.throttle';
/**
* Create a new router instance.
*
* @param \Illuminate\Events\Dispatcher $events
* @param \Dingo\Api\Routing\Config $config
* @param \Illuminate\Container\Container $container
* @return void
*/
public function __construct(Dispatcher $events, Config $config, Container $container = null)
{
$this->config = $config;
$this->api = new GroupCollection($config);
parent::__construct($events, $container);
}
/**
* Register an API group.
*
* @param array|string $options
* @param callable $callback
* @return void
* @throws \BadMethodCallException
*/
public function api($options, callable $callback)
{
$options = $this->setupGroupOptions($options);
$this->createRouteCollections($options);
$this->group($options, $callback);
}
/**
* Create the route collections with the given options.
*
* @param array $options
* @return void
*/
protected function createRouteCollections(array $options)
{
foreach ($options['version'] as $version) {
$this->api->add($version, $options);
}
}
/**
* Setup the API group options.
*
* @param array|string $options
* @return array
*/
protected function setupGroupOptions($options)
{
if (is_string($options)) {
$options = ['version' => $options];
} elseif (! isset($options['version'])) {
throw new BadMethodCallException('Unable to register API route group without a version.');
}
$options['api'] = true;
$options['version'] = (array) $options['version'];
if (! isset($options['prefix'])) {
$options['prefix'] = $this->config->getPrefix();
}
if (! isset($options['domain'])) {
$options['domain'] = $this->config->getDomain();
}
if (isset($options['conditional_request'])) {
$this->conditionalRequest = $options['conditional_request'];
}
return $options;
}
/**
* Determine if the router is currently routing to the API.
*
* @return bool
*/
protected function routingToApi()
{
return ! empty($this->groupStack) && array_get(last($this->groupStack), 'api', false) === true;
}
/**
* Dispatch the request to the application and return either a regular response
* or an API response.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response|\Dingo\Api\Http\Response
* @throws \Exception
*/
public function dispatch(Request $request)
{
if (! $this->isApiRequest($request)) {
return parent::dispatch($request);
}
list ($version, $format) = $this->parseAcceptHeader($request);
$this->currentVersion = $version;
$this->currentFormat = $format;
$this->container->instance('Illuminate\Http\Request', $request);
try {
$response = parent::dispatch($request);
// If the request is internal then we don't need to run the response
// through the formatter as an internal request will get the
// raw response that was returned.
if ($request instanceof InternalRequest) {
return $response;
// We'll try to set the request and the response on the formatter
// now so that we can catch any exceptions that may be thrown
// due to a badly requested format.
} else {
$response->getFormatter($format)
->setRequest($request)
->setResponse($response);
}
} catch (Exception $exception) {
if ($request instanceof InternalRequest) {
throw $exception;
} else {
$response = $this->prepareResponse(
$request,
$this->events->until('router.exception', [$exception])
);
// When an exception is thrown it halts execution of the dispatch. We'll
// call the attached after filters for caught exceptions still.
$this->callFilter('after', $request, $response);
}
}
// This goes hand in hand with the above. We'll check to see if a
// formatter exists for the requested response format. If not
// then we'll revert to the default format because we are
// most likely formatting an error response.
$format = $response->hasFormatter($format) ? $format : $this->defaultFormat;
return $response->morph($format);
}
/**
* {@inheritDoc}
*/
protected function newRoute($methods, $uri, $action)
{
if ($this->routingToApi()) {
return new Route($methods, $uri, $action);
}
return parent::newRoute($methods, $uri, $action);
}
/**
* Add a new route to either the routers collection or an API collection.
*
* @param array|string $methods
* @param string $uri
* @param callable|array|string $action
* @return \Illuminate\Routing\Route
*/
protected function addRoute($methods, $uri, $action)
{
$route = $this->createRoute($methods, $uri, $action);
if ($this->routingToApi()) {
return $this->addApiRoute($this->attachApiFilters($route));
}
return $this->routes->add($route);
}
/**
* Add a new route to an API collection.
*
* @param \Illuminate\Routing\Route $route
* @return \Illuminate\Routing\Route
*/
protected function addApiRoute($route)
{
$options = last($this->groupStack);
foreach ($this->api->getByOptions($options) as $collection) {
$collection->add($route);
}
return $route;
}
/**
* Attach the API before filters to the route.
*
* @param \Dingo\Api\Routing\Route $route
* @return \Dingo\Api\Routing\Route
*/
protected function attachApiFilters(Route $route)
{
$filters = $route->beforeFilters();
foreach ([static::API_FILTER_AUTH, static::API_FILTER_THROTTLE] as $filter) {
if (! isset($filters[$filter])) {
$route->before($filter);
}
}
return $route;
}
/**
* {@inheritDoc}
*/
protected function findRoute($request)
{
if ($this->isApiRequest($request)) {
$route = $this->api->getByVersion($this->currentVersion)->match($request);
} else {
$route = $this->routes->match($request);
}
return $this->current = $this->substituteBindings($route);
}
/**
* {@inheritDoc}
*/
protected function prepareResponse($request, $response)
{
if ($response instanceof ResponseBuilder) {
$response = $response->build();
}
$response = parent::prepareResponse($request, $response);
if ($this->isApiRequest($request)) {
if ($response instanceof IlluminateResponse) {
$response = ApiResponse::makeFromExisting($response);
}
if ($response->isSuccessful() && $this->requestsAreConditional()) {
if (! $response->headers->has('ETag')) {
$response->setEtag(md5($response->getContent()));
}
$response->isNotModified($request);
}
}
return $response;
}
/**
* Determine if the request is an API request.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
public function isApiRequest($request)
{
if ($this->api->isEmpty()) {
return false;
} elseif (isset($this->apiRequests[$key = sha1($request)])) {
return $this->apiRequests[$key];
}
$collection = $this->api->getByRequest($request) ?: $this->api->getDefault();
try {
$collection->match($request);
} catch (NotFoundHttpException $exception) {
return $this->apiRequests[$key] = false;
} catch (MethodNotAllowedHttpException $exception) {
// If a method is not allowed then we can say that a route was matched
// so the request is still targetting the API. This allows developers
// to provide better error responses when clients send bad requests.
}
return $this->apiRequests[$key] = true;
}
/**
* Parse a requests accept header.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
protected function parseAcceptHeader(Request $request)
{
if (preg_match('#application/vnd\.'.$this->config->getVendor().'.(v[\d\.]+)\+(\w+)#', $request->header('accept'), $matches)) {
return array_slice($matches, 1);
} elseif ($this->isStrict()) {
throw new InvalidAcceptHeaderException('Unable to match the "Accept" header for the API request.');
}
return [$this->config->getVersion(), $this->config->getFormat()];
}
/**
* Get the current API format.
*
* @return string
*/
public function getCurrentFormat()
{
return $this->currentFormat;
}
/**
* Get the current API version.
*
* @return string
*/
public function getCurrentVersion()
{
return $this->currentVersion;
}
/**
* Get a controller inspector instance.
*
* @return \Dingo\Api\Routing\ControllerInspector
*/
public function getInspector()
{
return $this->inspector ?: $this->inspector = new ControllerInspector;
}
/**
* Set the current request.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
public function setCurrentRequest(Request $request)
{
$this->currentRequest = $request;
}
/**
* Set the current route.
*
* @param \Illuminate\Routing\Route $route
* @return void
*/
public function setCurrentRoute(IlluminateRoute $route)
{
$this->current = $route;
}
/**
* Get the API groups collection containing the API routes.
*
* @return \Dingo\Api\Routing\GroupCollection
*/
public function getApiGroups()
{
return $this->api;
}
/**
* Determine if conditional requests are enabled.
*
* @return string
*/
public function requestsAreConditional()
{
return $this->conditionalRequest;
}
/**
* Enable or disable conditional requests.
*
* @param bool $conditionalRequest
* @return void
*/
public function setConditionalRequest($conditionalRequest)
{
$this->conditionalRequest = $conditionalRequest;
}
/**
* Determine if the request should be treated as strict.
*
* @return bool
*/
public function isStrict()
{
return $this->strict;
}
/**
* Enable or disable strict mode.
*
* @param bool $strict
* @return void
*/
public function setStrict($strict)
{
$this->strict = $strict;
}
}