LiaisonRouter.php

<?php

namespace Phad\Integration;

class LiaisonRouter implements \Phad\RouterInterface {

    protected \Lia\Addon\Router $lia_router;
    protected \Lia\Addon\Resources $lia_resources;
    protected \Phad $phad;

    public function __construct(\Lia $liaison){

        $this->lia_router = \Lia\Addon\Router::from($liaison);
        $this->lia_resources = \Lia\Addon\Resources::from($liaison);
    }

    public function set_phad_object(\Phad $phad){
        $this->phad = $phad;
    }
    public function add_route(string $pattern, array $methods){
        $at_methods = array_map(function($v){return '@'.$v.'.';}, $methods);
        $full_pattern = implode("", $at_methods).$pattern;
        $this->lia_router->addRoute($full_pattern, [$this,'handle_liaison_route']);
    }
    public function add_file_route(string $pattern, string $file_path, array $methods){
        $at_methods = array_map(function($v){return '@'.$v.'.';}, $methods);
        $full_pattern = implode("", $at_methods).$pattern;
        $this->lia_router->addRoute($full_pattern, $file_path);
    }

    public function handle_liaison_route(\Lia\Obj\Route $route, $response){
        $phad = $this->phad;
        $routes = $phad->routes_from_cache($this->phad->force_compile);

        // remove @GET.@POST. from the beginning
        $pattern = substr($route->paramaterizedPattern(), 11);

        $item_name = $routes[$pattern];
        $phad_response = $phad->get_response($route->paramaters(), $item_name);

        $item = $phad_response['view'];

        // print_r($item->resource_files());
        // exit;
        $resources = $this->lia_resources;
        foreach ($item->resource_files() as $type=>$list){
            foreach ($list as $path){
                $resources->addFile($path);
            }
        }

        $response->content = $phad_response['content'];
        if (!empty($phad_response['headers'])){
            $response->headers = $phad_response['headers'];
        }
    }
}