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