<?php
namespace Lia\Addon;
/**
* How will this be used?
* Show error at top of current page
* Redirect to error page with (or without) a message
* Show error page instead of requested page (no redirect)
* Log an error
*/
class Error extends \Lia\Addon {
public string $fqn = 'lia:server.error';
public $headerError = false;
protected ?int $statusCode = null;
public ?string $pageMessage = null;
public ?string $headerMessage = null;
public ?string $gotoMessage = null;
protected ?bool $isPageError = false;
public function init_lia(){
$lia = $this->lia;
// $this->hook('ResponseReady', [$this, 'onResponseReady']);
}
public function onPackageReady(){
\Lia\Addon\Hook::from($this->lia)
->add(\Lia\Hooks::RESPONSE_READY, [$this, 'onResponseReady']);
}
/**
*
*/
public function error_goto(string $message, int $statusCode=500){
// call the redirect component
$this->gotoMessage = $message;
$this->statusCode = $statusCode;
}
public function error_log(string $message, int $level){
// Where do we write logs?
}
public function error_header(string $message, ?int $statusCode=null){
// I need a callback to display the error header to
// Maybe with an error view (yes yes yes)
$this->headerMessage = $message;
$this->statusCode = $statusCode;
}
public function error_page(string $message, int $statusCode=500){
$this->statusCode = $statusCode;
$this->pageMessage = $message;
}
public function onResponseReady(\Lia\Obj\Response $response){
if ($this->gotoMessage!=null){
throw new \Exception("Error::goto message is not yet setup");
return;
}
if ($this->statusCode!=null){
$response->addHeader('HTTP/1.0 '.$this->statusCode.' '.$this->statusCodeText($this->statusCode));
}
if ($this->pageMessage!==null){
$response->content = \Lia\Addon\View::from($this->lia)
->view('error/page', ['message'=>$this->pageMessage]);
}
}
public function statusCodeText(int $statusCode){
static $codes = null;
// if ($codes===null)$codes = require($this->package->dir().'/file/http_status_codes.php');
if ($codes===null)$codes = require(dirname(__DIR__).'/file/http_status_codes.php');
return $codes[$statusCode] ?? '';
}
}