xref: /webtrees/app/Http/Middleware/Router.php (revision 5d4b7ec24d2b390be41475c9b93e00d957e93fef)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2020 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\Middleware;
21
22use Aura\Router\RouterContainer;
23use Fisharebest\Webtrees\Services\ModuleService;
24use Fisharebest\Webtrees\Services\TreeService;
25use Fisharebest\Webtrees\Tree;
26use Middleland\Dispatcher;
27use Psr\Http\Message\ResponseInterface;
28use Psr\Http\Message\ServerRequestInterface;
29use Psr\Http\Server\MiddlewareInterface;
30use Psr\Http\Server\RequestHandlerInterface;
31
32use function app;
33use function array_map;
34
35/**
36 * Simple class to help migrate to a third-party routing library.
37 */
38class Router implements MiddlewareInterface
39{
40    /** @var ModuleService */
41    private $module_service;
42
43    /** @var RouterContainer */
44    private $router_container;
45
46    /** @var TreeService */
47    private $tree_service;
48
49    /**
50     * Router constructor.
51     *
52     * @param ModuleService   $module_service
53     * @param RouterContainer $router_container
54     * @param TreeService     $tree_service
55     */
56    public function __construct(ModuleService $module_service, RouterContainer $router_container, TreeService $tree_service)
57    {
58        $this->module_service   = $module_service;
59        $this->router_container = $router_container;
60        $this->tree_service     = $tree_service;
61    }
62
63    /**
64     * @param ServerRequestInterface  $request
65     * @param RequestHandlerInterface $handler
66     *
67     * @return ResponseInterface
68     */
69    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
70    {
71        // Turn the ugly URL into a pretty one, so the router can parse it.
72        $pretty = $request;
73
74        if ($request->getAttribute('rewrite_urls') !== '1') {
75            // Ugly URLs store the path in a query parameter.
76            $url_route = $request->getQueryParams()['route'] ?? '';
77            $uri       = $request->getUri()->withPath($url_route);
78            $pretty    = $request->withUri($uri);
79        }
80
81        // Match the request to a route.
82        $route = $this->router_container->getMatcher()->match($pretty);
83
84        // No route matched? Let the default handler take care of it
85        if ($route === false) {
86            return $handler->handle($request);
87        }
88
89        // Add the route as attribute of the request
90        $request = $request->withAttribute('route', $route);
91
92        // This middleware cannot run until after the routing, as it needs to know the route.
93        $post_routing_middleware = [CheckCsrf::class];
94        $post_routing_middleware = array_map('app', $post_routing_middleware);
95
96        // Firstly, apply the route middleware
97        $route_middleware = $route->extras['middleware'] ?? [];
98        $route_middleware = array_map('app', $route_middleware);
99
100        // Secondly, apply any module middleware
101        $module_middleware = $this->module_service->findByInterface(MiddlewareInterface::class)->all();
102
103        // Finally, run the handler using middleware
104        $handler_middleware = [new WrapHandler($route->handler)];
105
106        $middleware = array_merge(
107            $post_routing_middleware,
108            $route_middleware,
109            $module_middleware,
110            $handler_middleware
111        );
112
113        // Add the matched attributes to the request.
114        foreach ($route->attributes as $key => $value) {
115            if ($key === 'tree') {
116                $value = $this->tree_service->all()->get($value);
117                app()->instance(Tree::class, $value);
118
119                // Missing mandatory parameter? Let the default handler take care of it.
120                if ($value === null && strpos($route->path, '{tree}') !== false) {
121                    return $handler->handle($request);
122                }
123            }
124
125            $request = $request->withAttribute((string) $key, $value);
126        }
127
128        // Bind the request into the container
129        app()->instance(ServerRequestInterface::class, $request);
130
131        $dispatcher = new Dispatcher($middleware, app());
132
133        return $dispatcher->dispatch($request);
134    }
135}
136