xref: /webtrees/app/Http/Middleware/Router.php (revision 541cf44d763a8aa5906f3fce58ca6b0ac3a25986)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 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 <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\Middleware;
21
22use Aura\Router\RouterContainer;
23use Aura\Router\Rule\Accepts;
24use Aura\Router\Rule\Allows;
25use Fig\Http\Message\StatusCodeInterface;
26use Fisharebest\Webtrees\Services\ModuleService;
27use Fisharebest\Webtrees\Services\TreeService;
28use Fisharebest\Webtrees\Tree;
29use Fisharebest\Webtrees\Validator;
30use Fisharebest\Webtrees\Webtrees;
31use Psr\Http\Message\ResponseInterface;
32use Psr\Http\Message\ServerRequestInterface;
33use Psr\Http\Server\MiddlewareInterface;
34use Psr\Http\Server\RequestHandlerInterface;
35
36use function app;
37use function response;
38use function str_contains;
39
40/**
41 * Simple class to help migrate to a third-party routing library.
42 */
43class Router implements MiddlewareInterface
44{
45    private ModuleService $module_service;
46
47    private RouterContainer $router_container;
48
49    private TreeService $tree_service;
50
51    /**
52     * Router constructor.
53     *
54     * @param ModuleService   $module_service
55     * @param RouterContainer $router_container
56     * @param TreeService     $tree_service
57     */
58    public function __construct(
59        ModuleService $module_service,
60        RouterContainer $router_container,
61        TreeService $tree_service
62    ) {
63        $this->module_service   = $module_service;
64        $this->router_container = $router_container;
65        $this->tree_service     = $tree_service;
66    }
67
68    /**
69     * @param ServerRequestInterface  $request
70     * @param RequestHandlerInterface $handler
71     *
72     * @return ResponseInterface
73     */
74    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
75    {
76        // Turn the ugly URL into a pretty one, so the router can parse it.
77        $pretty = $request;
78
79        if (!Validator::attributes($request)->boolean('rewrite_urls', false)) {
80            // Ugly URLs store the path in a query parameter.
81            $url_route = $request->getQueryParams()['route'] ?? '';
82            $uri       = $request->getUri()->withPath($url_route);
83            $pretty    = $request->withUri($uri);
84        }
85
86        // Match the request to a route.
87        $matcher = $this->router_container->getMatcher();
88        $route   = $matcher->match($pretty);
89
90        // No route matched?
91        if ($route === false) {
92            $failed_route = $matcher->getFailedRoute();
93
94            switch ($failed_route->failedRule) {
95                case Allows::class:
96                    return response('', StatusCodeInterface::STATUS_METHOD_NOT_ALLOWED, [
97                        'Allow' => implode(', ', $failed_route->allows),
98                    ]);
99
100                case Accepts::class:
101                    // We don't use this, but modules might.
102                    return response('Negotiation failed', StatusCodeInterface::STATUS_NOT_ACCEPTABLE);
103
104                default:
105                    // Not found
106                    return $handler->handle($request);
107            }
108        }
109
110        // Add the route as attribute of the request
111        $request = $request->withAttribute('route', $route);
112
113        // This middleware cannot run until after the routing, as it needs to know the route.
114        $post_routing_middleware = [CheckCsrf::class];
115
116        // Firstly, apply the route middleware
117        $route_middleware = $route->extras['middleware'] ?? [];
118
119        // Secondly, apply any module middleware
120        $module_middleware = $this->module_service->findByInterface(MiddlewareInterface::class)->all();
121
122        // Finally, run the handler using middleware
123        $handler_middleware = [RequestHandler::class];
124
125        $middleware = array_merge(
126            $post_routing_middleware,
127            $route_middleware,
128            $module_middleware,
129            $handler_middleware
130        );
131
132        // Add the matched attributes to the request.
133        foreach ($route->attributes as $key => $value) {
134            if ($key === 'tree') {
135                $value = $this->tree_service->all()->get($value);
136                app()->instance(Tree::class, $value);
137
138                // Missing mandatory parameter? Let the default handler take care of it.
139                if ($value === null && str_contains($route->path, '{tree}')) {
140                    return $handler->handle($request);
141                }
142            }
143
144            $request = $request->withAttribute((string) $key, $value);
145        }
146
147        // Bind the updated request into the container
148        app()->instance(ServerRequestInterface::class, $request);
149
150        return Webtrees::dispatch($request, $middleware);
151    }
152}
153