xref: /webtrees/app/Http/Middleware/Router.php (revision 0c0910bf0f275a14f35d2ccdf698f91f79e269d4)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 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 */
17declare(strict_types=1);
18
19namespace Fisharebest\Webtrees\Http\Middleware;
20
21use Aura\Router\RouterContainer;
22use Fisharebest\Webtrees\Services\ModuleService;
23use Fisharebest\Webtrees\Services\TreeService;
24use Fisharebest\Webtrees\Tree;
25use Fisharebest\Webtrees\View;
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;
34use function http_build_query;
35
36use const PHP_QUERY_RFC3986;
37
38/**
39 * Simple class to help migrate to a third-party routing library.
40 */
41class Router implements MiddlewareInterface
42{
43    /** @var ModuleService */
44    private $module_service;
45
46    /** @var RouterContainer */
47    private $router_container;
48
49    /** @var TreeService */
50    private $tree_service;
51
52    /**
53     * Router constructor.
54     *
55     * @param ModuleService   $module_service
56     * @param RouterContainer $router_container
57     * @param TreeService     $tree_service
58     */
59    public function __construct(ModuleService $module_service, RouterContainer $router_container, TreeService $tree_service)
60    {
61        $this->module_service   = $module_service;
62        $this->router_container = $router_container;
63        $this->tree_service     = $tree_service;
64    }
65
66    /**
67     * @param ServerRequestInterface  $request
68     * @param RequestHandlerInterface $handler
69     *
70     * @return ResponseInterface
71     */
72    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
73    {
74        if ((bool) $request->getAttribute('rewrite_urls') === false) {
75            // Turn the ugly URL into a pretty one, so the router can parse it.
76            // Note that the 'route' parameter contains the full path.
77            $uri       = $request->getUri();
78            $params    = $request->getQueryParams();
79            $url_route = $params['route'] ?? '/';
80            $uri       = $uri->withPath($url_route);
81            unset($params['route']);
82            $uri     = $uri->withQuery(http_build_query($params, '', '&', PHP_QUERY_RFC3986));
83            $temp_request = $request->withUri($uri)->withQueryParams($params);
84        } else {
85            $temp_request = $request;
86        }
87
88        // Match the request to a route.
89        $route = $this->router_container->getMatcher()->match($temp_request);
90
91        // No route matched?
92        if ($route === false) {
93            // Bind the request into the container and the layout
94            app()->instance(ServerRequestInterface::class, $request);
95            View::share('request', $request);
96
97            return $handler->handle($request);
98        }
99
100        // Add the route as attribute of the request
101        $request = $request->withAttribute('route', $route->name);
102
103        // Firstly, apply the route middleware
104        $route_middleware = $route->extras['middleware'] ?? [];
105        $route_middleware = array_map('app', $route_middleware);
106
107        // Secondly, apply any module middleware
108        $module_middleware = $this->module_service->findByInterface(MiddlewareInterface::class)->all();
109
110        // Finally, run the handler using middleware
111        $handler_middleware = [new WrapHandler($route->handler)];
112
113        $middleware = array_merge($route_middleware, $module_middleware, $handler_middleware);
114
115        // Add the matched attributes to the request.
116        foreach ($route->attributes as $key => $value) {
117            if ($key === 'tree') {
118                $value = $this->tree_service->findByName($value);
119                // @TODO - this is still required by the date formatter.
120                app()->instance(Tree::class, $value);
121                // @TODO - this is still required by various view templates.
122                View::share('tree', $value);
123            }
124            $request = $request->withAttribute($key, $value);
125        }
126
127        // Bind the request into the container and the layout
128        app()->instance(ServerRequestInterface::class, $request);
129        View::share('request', $request);
130
131        $dispatcher = new Dispatcher($middleware, app());
132
133        return $dispatcher->dispatch($request);
134    }
135}
136