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