diff --git a/composer.json b/composer.json index c0ba94e..b8f9511 100644 --- a/composer.json +++ b/composer.json @@ -25,12 +25,13 @@ "email": "aaron@trowski.com" } ], + "minimum-stability": "dev", "require": { "php": ">=8.1", "amphp/amp": "^3", "amphp/cache": "^2", - "amphp/http": "^2", - "amphp/http-server": "^3", + "amphp/http": "dev-structured-fields as v2.1.0", + "amphp/http-server": "dev-http3 as 3.1", "amphp/socket": "^2", "nikic/fast-route": "^1", "psr/log": "^1|^2|^3" diff --git a/src/Router.php b/src/Router.php index b60409f..a03e3e5 100644 --- a/src/Router.php +++ b/src/Router.php @@ -6,13 +6,18 @@ use Amp\ForbidCloning; use Amp\ForbidSerialization; use Amp\Http\HttpStatus; +use Amp\Http\Server\Driver\Client; +use Amp\Http\Server\Driver\HttpDriver; +use Amp\Http\Server\Driver\HttpDriverFactory; +use Amp\Http\Server\Driver\HttpDriverMergedFactory; +use Amp\Http\Server\Driver\HttpDriverMiddleware; use Amp\Http\Server\RequestHandler\ClosureRequestHandler; use FastRoute\Dispatcher; use FastRoute\RouteCollector; use Psr\Log\LoggerInterface; use function FastRoute\simpleDispatcher; -final class Router implements RequestHandler +final class Router implements RequestHandler, HttpDriverMiddleware { use ForbidCloning; use ForbidSerialization; @@ -113,6 +118,26 @@ public function handleRequest(Request $request): Response } } + public function createHttpDriver(HttpDriverFactory $factory, RequestHandler $requestHandler, ErrorHandler $errorHandler, Client $client): HttpDriver + { + $middlewares = []; + foreach ($this->routes as [, , $routeHandler]) { + if ($requestHandler instanceof HttpDriverMiddleware) { + $middlewares[] = $routeHandler; + } + } + + if ($middlewares) { + if (count($middlewares) == 1) { + return $middlewares[0]->createHttpDriver($factory, $requestHandler, $errorHandler, $client); + } + + $factory = new HttpDriverMergedFactory($middlewares, $factory); + } + + return $factory->createHttpDriver($requestHandler, $errorHandler, $client); + } + /** * Merge another router's routes into this router. *