seria/src/RoutingContext.php

50 lines
1.5 KiB
PHP
Raw Normal View History

<?php
namespace Seria;
use Index\Http\HttpFx;
use Index\Http\HttpResponseBuilder;
use Index\Http\HttpRequest;
use Index\Routing\IRouter;
use Index\Routing\IRouteHandler;
class RoutingContext {
private HttpFx $router;
public function __construct() {
$this->router = new HttpFx;
$this->router->use('/', fn($resp) => $resp->setPoweredBy('Seria'));
}
public function getRouter(): IRouter {
return $this->router;
}
public function registerDefaultErrorPages(): void {
$this->router->setDefaultErrorHandler($this->defaultErrorHandler(...));
$this->router->addErrorHandler(500, fn($resp) => $resp->setContent(file_get_contents(SERIA_DIR_TEMPLATES . '/500.html')));
}
public function defaultErrorHandler(
HttpResponseBuilder $responseBuilder,
HttpRequest $request,
int $code,
string $message
): void {
// todo: render using templating
$responseBuilder->setTypeHTML();
$responseBuilder->setContent(sprintf(
'<!doctype html><html><head><meta charset="utf-8"/><title>%1$03d %2$s</title></head><body><center><h1>%1$03d %2$s</h1></center><hr/><center>Seria</center></body></html>',
$code,
$message
));
}
public function register(IRouteHandler $handler): void {
$this->router->register($handler);
}
public function dispatch(?HttpRequest $request = null): void {
$this->router->dispatch($request);
}
}