Error.php

<?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;
        $lia->methods['error_header'] = [$this, 'error_header'];
        $lia->methods['error_page'] = [$this, 'error_page'];
        $lia->methods['error_goto'] = [$this, 'error_goto'];

        // $this->lia->props['hooks']['ResponseReady'][] = [$this, 'onResponseReady'];
        // $this->hook('ResponseReady', [$this, 'onResponseReady']);
    }
    public function onPackageReady(){
        $this->lia->scan('on', $this);
    }
    
    /**
     * 
     */
    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($response){
        if ($this->gotoMessage!=null){
            throw new \Exception("Error::goto message is not yet setup");
            $this->lia->api('lia:goto.withMessage', $this->errorUrl(), $this->gotoMessage);
            $this->lia->api('lia:goto.setHeadersNow');
            return;
        }
        if ($this->statusCode!=null){
            $response->addHeader('HTTP/1.0 '.$this->statusCode.' '.$this->statusCodeText($this->statusCode));
        }

        if ($this->pageMessage!==null){
            $response->content = $this->lia->api('lia:view.get','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] ?? '';
    }
}