-
-
Notifications
You must be signed in to change notification settings - Fork 829
/
ResolveRoute.php
66 lines (55 loc) · 2 KB
/
ResolveRoute.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
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Http\Middleware;
use FastRoute\Dispatcher;
use Flarum\Http\Exception\MethodNotAllowedException;
use Flarum\Http\Exception\RouteNotFoundException;
use Flarum\Http\RouteCollection;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface as Middleware;
use Psr\Http\Server\RequestHandlerInterface as Handler;
class ResolveRoute implements Middleware
{
protected ?Dispatcher\GroupCountBased $dispatcher = null;
public function __construct(
protected RouteCollection $routes
) {
}
/**
* Resolve the given request from our route collection.
*
* @throws MethodNotAllowedException
* @throws RouteNotFoundException
*/
public function process(Request $request, Handler $handler): Response
{
$method = $request->getMethod();
$uri = $request->getUri()->getPath() ?: '/';
$routeInfo = $this->getDispatcher()->dispatch($method, $uri);
switch ($routeInfo[0]) {
case Dispatcher::NOT_FOUND:
throw new RouteNotFoundException($uri);
case Dispatcher::METHOD_NOT_ALLOWED:
throw new MethodNotAllowedException($method);
default:
$request = $request
->withAttribute('routeName', $routeInfo[1]['name'])
->withAttribute('routeHandler', $routeInfo[1]['handler'])
->withAttribute('routeParameters', $routeInfo[2]);
return $handler->handle($request);
}
}
protected function getDispatcher(): Dispatcher\GroupCountBased
{
if (! isset($this->dispatcher)) {
$this->dispatcher = new Dispatcher\GroupCountBased($this->routes->getRouteData());
}
return $this->dispatcher;
}
}