getCode()); foreach ($response->getHeaders() as $header => $value) { header("$header: $value"); } if ($response instanceof ViewHttpResponse) { self::renderView($response, $twigSupplier); } elseif ($response instanceof JsonHttpResponse) { header('Content-type: application/json'); echo $response->getJson(); } } /** * renders (prints out) given ViewHttpResponse to the client * @param ViewHttpResponse $response * @param callable(): Environment $twigSupplier * @return void * @throws LoaderError * @throws RuntimeError * @throws SyntaxError */ private static function renderView(ViewHttpResponse $response, callable $twigSupplier): void { $file = $response->getFile(); $args = $response->getArguments(); switch ($response->getViewKind()) { case ViewHttpResponse::REACT_VIEW: send_react_front($file, $args); break; case ViewHttpResponse::TWIG_VIEW: try { $twig = call_user_func($twigSupplier); $twig->display($file, $args); } catch (RuntimeError|SyntaxError|LoaderError $e) { http_response_code(500); echo "There was an error rendering your view, please refer to an administrator.\nlogs date: " . date("YYYD, d M Y H:i:s"); throw $e; } break; } } /** * run a user action, and return the generated response * @param string $authRoute the route towards an authentication page to response with a redirection * if the run action requires auth but session does not contain a logged-in account. * @param Action $action * @param mixed[] $params * @param MutableSessionHandle $session * @return HttpResponse */ public static function runAction(string $authRoute, Action $action, array $params, MutableSessionHandle $session): HttpResponse { if ($action->getAuthType() != Action::NO_AUTH) { $account = $session->getAccount(); if ($account == null) { // put in the session the initial url the user wanted to get $session->setInitialTarget($_SERVER['REQUEST_URI']); return HttpResponse::redirectAbsolute($authRoute); } if ($action->getAuthType() == Action::AUTH_ADMIN && !$account->getUser()->isAdmin()) { return new JsonHttpResponse([ValidationFail::unauthorized()], HttpCodes::UNAUTHORIZED); } } return $action->run($params, $session); } }