. */ declare(strict_types=1); namespace Fisharebest\Webtrees\Http\Middleware; use Fig\Http\Message\RequestMethodInterface; use Fisharebest\Webtrees\Services\ModuleService; use Fisharebest\Webtrees\Webtrees; use Middleland\Dispatcher; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use function app; use function array_map; /** * Simple class to help migrate to a third-party routing library. */ class Router implements MiddlewareInterface, RequestMethodInterface { /** @var string[][] */ private $routes = [ self::METHOD_GET => [], self::METHOD_POST => [], ]; /** @var ModuleService */ private $module_service; /** * Router constructor. * * @param ModuleService $module_service */ public function __construct(ModuleService $module_service) { $this->module_service = $module_service; } /** * @param string $path * @param string $handler * * @return Router */ public function get(string $path, string $handler): Router { return $this->add(self::METHOD_GET, $path, $handler); } /** * @param string $method * @param string $path * @param string $handler * * @return Router */ private function add(string $method, string $path, string $handler): Router { $this->routes[$method][$path] = $handler; return $this; } /** * @param string $path * @param string $handler * * @return Router */ public function post(string $path, string $handler): Router { return $this->add(self::METHOD_POST, $path, $handler); } /** * @param ServerRequestInterface $request * @param RequestHandlerInterface $handler * * @return ResponseInterface */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { // Save the router in the container, as we'll need it to generate URLs. app()->instance(self::class, $this); // Load the routing table. require Webtrees::ROOT_DIR . 'routes/web.php'; // Match the request to a route. $method = $request->getMethod(); $route = $request->getQueryParams()['route'] ?? ''; $routing = $this->routes[$method][$route] ?? ''; // Bind the request into the container app()->instance(ServerRequestInterface::class, $request); // No route matched? if ($routing === '') { return $handler->handle($request); } // Firstly, apply the route middleware $route_middleware = []; $route_middleware = array_map('app', $route_middleware); // Secondly, apply any module middleware $module_middleware = $this->module_service->findByInterface(MiddlewareInterface::class)->all(); // Finally, run the handler using middleware $handler_middleware = [new WrapHandler($routing)]; $middleware = array_merge($route_middleware, $module_middleware, $handler_middleware); $dispatcher = new Dispatcher($middleware, app()); return $dispatcher->dispatch($request); } }