xref: /webtrees/app/Http/Middleware/Router.php (revision 44aaa5c310ca5c592c25fef66643ef0b8d0416c5)
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 Fig\Http\Message\RequestMethodInterface;
23use Fisharebest\Webtrees\Services\ModuleService;
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;
31use function app;
32use function array_map;
33use function parse_url;
34use const PHP_URL_PATH;
35
36/**
37 * Simple class to help migrate to a third-party routing library.
38 */
39class Router implements MiddlewareInterface, RequestMethodInterface
40{
41    /** @var ModuleService */
42    private $module_service;
43
44    /**
45     * Router constructor.
46     *
47     * @param ModuleService $module_service
48     */
49    public function __construct(ModuleService $module_service)
50    {
51        $this->module_service = $module_service;
52    }
53
54    /**
55     * @param ServerRequestInterface  $request
56     * @param RequestHandlerInterface $handler
57     *
58     * @return ResponseInterface
59     */
60    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
61    {
62        $base_url         = $request->getAttribute('base_url');
63        $base_path        = parse_url($base_url, PHP_URL_PATH) ?? '';
64        $router_container = new RouterContainer($base_path);
65
66        // Save the router in the container, as we'll need it to generate URLs.
67        app()->instance(RouterContainer::class, $router_container);
68
69        // Load the routing table.
70        require __DIR__ . '/../../../routes/web.php';
71
72        if ($request->getAttribute('rewrite_urls') !== '1') {
73            // Turn the ugly URL into a pretty one.
74            $params = $request->getQueryParams();
75            $route   = $params['route'] ?? '';
76            unset($params['route']);
77            $uri     = $request->getUri()->withPath($route);
78            $request = $request->withUri($uri)->withQueryParams($params);
79        }
80
81        // Bind the request into the container and the layout
82        app()->instance(ServerRequestInterface::class, $request);
83        View::share('request', $request);
84
85        // Match the request to a route.
86        $route = $router_container->getMatcher()->match($request);
87
88        // No route matched?
89        if ($route === false) {
90            return $handler->handle($request);
91        }
92
93        // Firstly, apply the route middleware
94        $route_middleware = $route->extras['middleware'] ?? [];
95        $route_middleware = array_map('app', $route_middleware);
96
97        // Secondly, apply any module middleware
98        $module_middleware = $this->module_service->findByInterface(MiddlewareInterface::class)->all();
99
100        // Add the route as attribute of the request
101        $request = $request->withAttribute('route', $route->name);
102
103        // Finally, run the handler using middleware
104        $handler_middleware = [new WrapHandler($route->handler)];
105
106        $middleware = array_merge($route_middleware, $module_middleware, $handler_middleware);
107
108        // Add the matched attributes to the request.
109        foreach ($route->attributes as $key => $value) {
110            if ($key === 'tree') {
111                $value = Tree::findByName($value);
112            }
113            $request = $request->withAttribute($key, $value);
114        }
115
116        $dispatcher = new Dispatcher($middleware, app());
117
118        return $dispatcher->dispatch($request);
119    }
120}
121