<?php
namespace Lia\Http;
/**
* Processes a route, modifying the response to produce output.
*
* @TODO create RouteHandler interface & allow configuring the RouteHandler class.
*/
class Responder {
/**
* Set true to allow executable files to respond to routes. Theme name is not changed when executable is used.
*/
public bool $allowExecutableFile = false;
public function __construct(){
}
public function respond_to_route(\Lia\Http\Request $request, \Lia\Http\Response $response, \Lia\Http\Route $route): void {
$target = $route->target;
if ($route->isCallable()){
ob_start();
$target($route);
$response->body = ob_get_clean();
} else if ($route->fileExt()=='php'){
$response->body =
$this->handle_php_route(
$request,
$response,
$route,
$route->args['lia'],
$route->args['app'],
$route->args['public_dir'],
$route->args,
//array_merge($route->router->route_args, $route->args),
);
} else if ($this->allowExecutableFile&&$route->isExecutableFile()){
ob_start();
system(escapeshellarg($route->target));
$response->body = ob_get_clean();
} else if ($route->isFile()){
$response->theme_name = 'raw';
$staticFile = new \Lia\Utility\StaticFile($target);
$headers = $staticFile->getHeaders();
foreach ($headers as $h){
header($h);
}
$response->body = file_get_contents($target);
} else {
// @todo consider alternate error handling for route not process-able
throw new \Exception("The Request could not be handled by '".get_class($this)."'");
}
}
/**
* Require a php file & return its output.
*
* @param $request
*
*
* @param $request \Lia\Http\Request
* @param $response \Lia\Http\Response
* @param $route \Lia\Http\Route
* @param $lia \Lia
* @param $app \Lia\AppInterface The app which added this route
* @param $public_dir string The public dir of the route's app.
* @param $args array arguments made available to routes in $app, and/or args made available to this specific route.
*/
public function handle_php_route(
\Lia\Http\Request $request,
\Lia\Http\Response $response,
\Lia\Http\Route $route,
\Lia $lia,
\Lia\AppInterface $app,
string $public_dir,
array $args,
): string {
ob_start();
require($route->target);
return ob_get_clean();
}
}