xref: /webtrees/app/Http/Middleware/Router.php (revision 89f7189b61a494347591c99bdb92afb7d8b66e1b)
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\Registry;
27use Fisharebest\Webtrees\Services\ModuleService;
28use Fisharebest\Webtrees\Services\TreeService;
29use Fisharebest\Webtrees\Tree;
30use Middleland\Dispatcher;
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 array_map;
38use function response;
39use function str_contains;
40
41/**
42 * Simple class to help migrate to a third-party routing library.
43 */
44class Router implements MiddlewareInterface
45{
46    /** @var ModuleService */
47    private $module_service;
48
49    /** @var RouterContainer */
50    private $router_container;
51
52    /** @var TreeService */
53    private $tree_service;
54
55    /**
56     * Router constructor.
57     *
58     * @param ModuleService   $module_service
59     * @param RouterContainer $router_container
60     * @param TreeService     $tree_service
61     */
62    public function __construct(ModuleService $module_service, RouterContainer $router_container, TreeService $tree_service)
63    {
64        $this->module_service   = $module_service;
65        $this->router_container = $router_container;
66        $this->tree_service     = $tree_service;
67    }
68
69    /**
70     * @param ServerRequestInterface  $request
71     * @param RequestHandlerInterface $handler
72     *
73     * @return ResponseInterface
74     */
75    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
76    {
77        // Turn the ugly URL into a pretty one, so the router can parse it.
78        $pretty = $request;
79
80        if ($request->getAttribute('rewrite_urls') !== '1') {
81            // Ugly URLs store the path in a query parameter.
82            $url_route = $request->getQueryParams()['route'] ?? '';
83            $uri       = $request->getUri()->withPath($url_route);
84            $pretty    = $request->withUri($uri);
85        }
86
87        // Match the request to a route.
88        $matcher = $this->router_container->getMatcher();
89        $route   = $matcher->match($pretty);
90
91        // No route matched?
92        if ($route === false) {
93            $failed_route = $matcher->getFailedRoute();
94
95            switch ($failed_route->failedRule) {
96                case Allows::class:
97                    return response('', StatusCodeInterface::STATUS_METHOD_NOT_ALLOWED, [
98                        'Allow' => implode(', ', $failed_route->allows),
99                    ]);
100
101                case Accepts::class:
102                    // We don't use this, but modules might.
103                    return response('Negotiation failed', StatusCodeInterface::STATUS_NOT_ACCEPTABLE);
104
105                default:
106                    // Not found
107                    return $handler->handle($request);
108            }
109        }
110
111        // Add the route as attribute of the request
112        $request = $request->withAttribute('route', $route);
113
114        // This middleware cannot run until after the routing, as it needs to know the route.
115        $post_routing_middleware = [CheckCsrf::class];
116        $post_routing_middleware = array_map('app', $post_routing_middleware);
117
118        // Firstly, apply the route middleware
119        $route_middleware = $route->extras['middleware'] ?? [];
120        $route_middleware = array_map('app', $route_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 = [new WrapHandler($route->handler)];
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 request into the container
151        app()->instance(ServerRequestInterface::class, $request);
152
153        $dispatcher = new Dispatcher($middleware, app());
154
155        // These are deprecated, and will be removed in webtrees 2.1.0
156        app()->instance('cache.array', Registry::cache()->array());
157        app()->instance('cache.files', Registry::cache()->file());
158
159        // These are deprecated, and will be removed in webtrees 2.1.0
160        $request = $request
161            ->withAttribute('filesystem.data', Registry::filesystem()->data())
162            ->withAttribute('filesystem.data.name', Registry::filesystem()->dataName())
163            ->withAttribute('filesystem.root', Registry::filesystem()->root())
164            ->withAttribute('filesystem.root.name', Registry::filesystem()->rootName());
165
166        return $dispatcher->dispatch($request);
167    }
168}
169