routes = new RouteCollection(); $this->configurator = new RouteConfigurator($this->routes, $this->routes); $this->addRoutes(); } /** * match the current url against the routes. * also add preflight CORS headers on OPTIONS requests. */ public function run(): Response { $request = Request::createFromGlobals(); if ($request->isMethod("OPTIONS")) { $response = new Response(); $response->headers->add([ "Access-Control-Allow-Origin" => "*", "Access-Control-Allow-Methods" => "GET, POST, PUT, DELETE, OPTIONS, PATCH, HEAD", "Access-Control-Allow-Headers" => "X-Requested-With, Content-Type, Authorization", ]); return $response; } $context = new RequestContext(); $context->fromRequest($request); try { $matcher = new UrlMatcher($this->routes, $context); $match = $matcher->matchRequest($request); $class = $match["_controller"][0]; $method = $match["_controller"][1]; return (new $class)->$method(); } catch (\Exception $exception) { return new ErrorResponse(ErrorCode::UNKNOWN, "Unknown error occured"); } } /** * add routes from the routes file */ private function addRoutes(): void { $routes = include_once(__DIR__ . "/routes.php"); $routes($this->configurator); } }