*/ private array $routes = []; /** @var MiddlewareInterface[] */ private array $middleware = []; public function addRoute(string $op, RequestHandlerInterface $handler): void { $this->routes[$op] = $handler; } public function addMiddleware(MiddlewareInterface $middleware): void { $this->middleware[] = $middleware; } /** * Dispatch an operation and send the response. * Calls exit after sending the response. */ public function dispatch(string $op): void { $response = $this->dispatchResponse($op); $response->send(); exit; } /** * Get the Response for a dispatch without sending it. * Used for testing and for cases where the caller * wants to modify the response before sending. */ public function dispatchResponse(string $op): Response { $handler = $this->routes[$op] ?? null; if (!$handler) { return (new Response()) ->withStatus(404) ->withBody(json_encode(["error" => "Method not found"])); } // Check auth for handlers that require it if ($handler instanceof AuthRequired && !validate_session()) { return (new Response()) ->withStatus(401) ->withBody(json_encode(["error" => "Unauthorized"])); } $pipe = $handler->handle(...); // wrap middleware in reverse order (last added = outermost) foreach (array_reverse($this->middleware) as $mw) { $previous = $pipe; $pipe = fn(Request $r) => $mw->process($r, $previous); } $request = new Request(); $request = $request->withAttribute('op', $op); return $pipe($request); } }