RouterListener::onRequest()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
cc 4
nc 4
nop 1
1
<?php
2
3
/*
4
 * This file is part of the jade/jade package.
5
 *
6
 * (c) Slince <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Jade\HttpKernel;
13
14
use FastRoute\Dispatcher;
15
use Jade\Exception\MethodNotAllowedHttpException;
16
use Jade\Exception\NotFoundHttpException;
17
use Jade\HttpKernel\Event\GetResponseEvent;
18
use Jade\Routing\Route;
19
use Jade\Routing\Router;
20
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
21
22
class RouterListener implements EventSubscriberInterface
23
{
24
    /**
25
     * @var Router
26
     */
27
    protected $router;
28
29
    public function __construct(Router $router)
30
    {
31
        $this->router = $router;
32
    }
33
34
    public static function getSubscribedEvents()
35
    {
36
        return [
37
            KernelEvents::MIDDLEWARE => 'onRequest'
38
        ];
39
    }
40
41
    public function onRequest(GetResponseEvent $event)
42
    {
43
        $request = $event->getRequest();
44
        $matches = $this->router->dispatch($request);
45
        switch ($matches[0]) {
46
            case Dispatcher::FOUND:
47
                $route = $this->router->searchRoute($matches[1]);
48
                $this->prepareRoute($route, $matches);
49
                // 记录当前路由到指定请求体里
50
                $request = $request->withAttribute('_route', $route);
51
                break;
52
            case Dispatcher::METHOD_NOT_ALLOWED:
53
                $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)',
54
                    $request->getMethod(), $request->getUri()->getPath(),
55
                    implode(',', $matches[1])
56
                );
57
                throw new MethodNotAllowedHttpException($message);
58
            case Dispatcher::NOT_FOUND:
59
                $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getUri()->getPath());
60
                throw new NotFoundHttpException($message);
61
        }
62
        $event->setRequest($request);
63
    }
64
65
    /**
66
     * 预处理 route
67
     *
68
     * @param Route $route
69
     * @param array $matches
70
     */
71
    protected function prepareRoute(Route $route, $matches)
72
    {
73
        $routeArguments = [];
74
        foreach ($matches[2] as $k => $v) {
75
            $routeArguments[$k] = urldecode($v);
76
        }
77
        $route->setArguments($routeArguments);
78
    }
79
}