Router.php

<?php

namespace Lia\Compo;

/**
 * @todo handleBlog(){} to respond to a request, routeBlog(){} to get an array of routes (which auto-point to handleBlog(){}))
 */
class Router extends \Lia\Compo {

    
    protected $varDelim = '\\.\\/';
    protected $routeMap = [];

    /**
     * Callables that can route a request & return false if they don't route
     */
    // protected $routers = [];


    public function onReady(){
        $lia = $this->lia;

        $lia->addApi('lia:route.add',[$this,'addRoute']);
        $lia->addApiMethod('lia:route.add', 'addRoute');

        $lia->addApi('lia:route.get', [$this,'route']);
        $lia->addApiMethod('lia:route.get', 'route');

        $lia->addApi('lia:route.deriveFromCallable',[$this,'deriveRouteUrls']);
        $lia->addApiPrefix('lia:route.deriveFromCallable', 'route');

    }

//
// APIs
//
    /**
     * Derive routes by calling functions with the `route` prefix
     */
    public function deriveRouteUrls($key, $callable){
        $patterns = $callable(false);
        // print_r($patterns);
        foreach ($patterns as $pattern){
            $this->lia->api('lia:route.add', $pattern, $callable);
        }
    }
    /**
     * Add a route
     * 
     * @param $pattern A pattern. See parsePattern()  documentation
     * @param $callbackOrFile a callback or a file path
     * @param $package (optional) A liaison package
     *
     */
    public function addRoute($pattern, $callbackOrFile,$package=null){
        $initialParsed = $this->parsePattern($pattern);
        $list = [$initialParsed];
        if (($initialParsed['extraParsedPattern']??false)){
            $extraParsed = $initialParsed;
            $extraParsed['parsedPattern'] = $extraParsed['extraParsedPattern'];
            $params = $extraParsed['params'];
            foreach ($extraParsed['optionalParams'] as $p){
                $index = array_search($p, $params);
                unset($params[$index]);
            }
            
            $params = array_values($params);
            $extraParsed['params'] = $params;
            
            $list[] = $extraParsed;
        }
        foreach ($list as $parsed){
            $parsed['target'] = $callbackOrFile;
            $parsed['package'] = $package;
            $testPattern = $parsed['parsedPattern'];
            $matches = [];
            foreach ($parsed['methods'] as $m){
                $this->routeMap[$m][$testPattern][] = $parsed;
            }            
        }
    }

    /**
     *  get a route for the given request
     *
     *  @todo write test for routing via added routers
     */
    public function route(\Lia\Obj\Request $request){
        $url = $request->url();
        $method = $request->method();

        if ($this->lia->hasApi('lia:config.get'))
        foreach ($this->lia->api('lia:config.get', 'lia:route.routers', []) as $r){
            if ($routeList = $r($request)){
                return $routeList;
            }
        }
        
        $testReg = $this->urlToTestReg($url);
        $all = array_filter($this->routeMap[$method]??[],
            function($routeList,$parsedPattern) use ($testReg) {
                if (preg_match('/'.$testReg.'/',$parsedPattern))return true;
                return false;
            }
            ,ARRAY_FILTER_USE_BOTH);
        $routeList = [];
        sort($all);
        $all = array_merge(...$all);
        foreach ($all as $routeInfo){
            $active = [
                'url' => $url,
                'method'=>$method,
                'urlRegex'=>$testReg
            ];
            $paramaters = null;
            $paramaters = $this->mapParamaters($routeInfo, $url);
            $optionalParamaters = $routeInfo['optionalParams']??[];
            $shared = [
                'paramaters'=>$paramaters,
                'optionalParamaters'=> $optionalParamaters,
            ];
            $static = [
                'allowedMethods'=>$routeInfo['methods'],
                'paramaterizedPattern'=>$routeInfo['pattern'],
                'placeholderPattern'=>$routeInfo['parsedPattern'],
                'target'=>$routeInfo['target'],
                'package'=>$routeInfo['package'],
            ];
            $route = new \Lia\Obj\Route(array_merge($active,$shared,$static));
            $routeList[] = $route;
        }
        return $routeList;
    }


//
// utility Functions
//



    /**
    * The patterns apply both for the `public` dir and by adding routes via `$lia->addRoute()`. The file extension (for .php) is removed prior to calling parsePattern()
    * 
    * ## Examples: 
    * - /blog/{category}/{post} is valid for url /blog/black-lives/matter
    * - /blog/{category}.{post}/ is valid for url /blog/environment.zero-waste/
    * - /blog/{category}{post}/ is valid for url /blog/{category}{post}/ and has NO dynamic paramaters
    * - /blog/{category}/@GET.{post}/ is valid for GET /blog/kindness/is-awesome/ but not for POST request
    * - /@POST.dir/sub/@GET.file/ is valid for both POST /dir/sub/file/ and GET /dir/sub/file/
    *
    * ## Methods: @POST, @GET, @PUT, @DELETE, @OPTIONS, @TRACE, @HEAD, @CONNECT
    * - We do not currently check the name of the method, just @ABCDEF for length 3-7
    * - These must appear after a `/` or after another '@METHOD.' or they will be taken literally
    * - lower case is not valid
    * - Each method MUST be followed by a period (.)
    * 
    * ## Paramaters:
    * - {under_scoreCamel} specifies a named, dynamic paramater
    * - {param} must be surrounded by path delimiters (/) OR periods (.) which will be literal characters in the url
    * - {param} MAY be at the end of a pattern with no trailing delimiter
    *
    * ## TODO
    * - {paramName:regex} would specify a dynamic portion of a url that MUST match the given regex. 
    *     - Not currently implemented
    * - {?param} would specify a paramater that is optional
    *     - Not currently implemented
    *
    * @export(Router.PatternRules)
    */
    public function parsePattern($pattern){

        $dlm = $this->varDelim;

        $params = [];
        $optionalParams = [];
        $replace = 
        function($matches) use (&$params, &$optionalParams){
            if ($matches[1]=='?'){
                $params[] = $matches[2];
                $optionalParams[] = $matches[2];
                return '#';                
            }
            $params[] = $matches[2];
            return '?';
        };
        $pieces = explode('/',$pattern);
        $methods = [];
        $testUrl = '';
        $extraTestUrl = '';
        foreach ($pieces as $piece){
            $startPiece = $piece;
            // extract @METHODS.
            while (preg_match('/^\@([A-Z]{3,7})\./',$piece,$methodMatches)){
                $method = $methodMatches[1];
                $len = strlen($method);
                $piece = substr($piece,2+$len);
                $methods[$methodMatches[1]] = $methodMatches[1];
            } 
            while ($piece!=($piece = preg_replace_callback('/(?<=^|['.$dlm.'])\{(\??)([a-zA-Z\_]+)\}(?=['.$dlm.']|$)/',$replace,$piece))){
            }
            if ($piece=='#'&&$startPiece!=$piece){
                $extraTestUrl .= '';// don't add anything.
                $piece = '?';
            } else {
                $extraTestUrl .= '/'.$piece;
            }
            $testUrl .= '/'.$piece;
        }

        $testUrl = str_replace(['///','//'],'/',$testUrl);
        $extraTestUrl = str_replace(['///','//'],'/',$extraTestUrl);
        
        $parsed = [
            'pattern'=>$pattern,
            'parsedPattern'=>$testUrl,
            'params'=>$params,
            'methods'=>count($methods)>0 ? $methods : ['GET'=>'GET'],
        ];
        
        if ($testUrl!=$extraTestUrl){
            $parsed['extraParsedPattern']=$extraTestUrl;
            $parsed['optionalParams'] = $optionalParams;
        }
        return $parsed;
    }

    /**
     * @param $parsedPattern expects the array generated by parsePattern(/url/pattern/)
     */
    public function mapParamaters($parsedPattern, $url){
        $phPattern = $parsedPattern['parsedPattern'];
        $staticPieces = explode('?',$phPattern);
        $staticPieces = array_map(function($piece){return preg_quote($piece,'/');}, $staticPieces);
        $dlm = $this->varDelim;
        $reg = "([^{$dlm}].*)";
        $asReg = '/'.implode($reg, $staticPieces).'/';
        preg_match($asReg,$url,$matches);
        $params = [];
        $i=1;
        foreach ($parsedPattern['params'] as $name){
            $params[$name] = $matches[$i++] ?? null;
            if ($params[$name]==null){
                echo "\n\nInternal Error. Please report a bug on https://github.com/Taeluf/Liaison/issues with the following:\n\n";
                echo "url: {$url}\nParsed Pattern:\n";
                print_r($parsedPattern);
                echo "\n\n";
                throw new \Lia\Exception\Base("Internal error. We were unable to perform routing for '{$url}'. ");
            }
        }

        return $params;
    }

    public function urlToTestReg($url){
        $dlm = $this->varDelim;
        $pieces = preg_split('/['.$dlm.']/',$url);
        array_shift($pieces);
        $last = array_pop($pieces);
        if ($last!='')$pieces[] = $last;
        $reg = '';
        $pos = 0;

        $test = '';
        foreach ($pieces as $p){
            $len = strlen($p)+1;
            $startDelim = substr($url,$pos,1);
            if ($p==''){
                $test .= '\\'.$startDelim;
                $pos += $len;
                continue;
            }
            $pEsc = preg_quote($p,'/');
            $pReg = '\\'.$startDelim.'(?:'.$pEsc.'|\?)';

            $pos += $len;
            $test .= $pReg;
        }
        $finalDelim = substr($url,$pos);
        $test .= $finalDelim ? '\\'.$finalDelim : '';
        $test = '^'.$test.'$';
        return $test;
    }

    /** 
     * Get a url from a parsed pattern & array of values to fill
     *
     * @param $parsed see parsePattern()
     * @param $withValues a `key=>value` array
     * @return the url with the paramaters inserted
     */ 
    public function fillPattern(array $parsed, array $withValues): string{
        $sorted = [];
        foreach ($parsed['params'] as $index=>$param){
            $sorted[$index] = $withValues[$param];
        }
        $filledPattern = $parsed['parsedPattern'];
        $val = reset($sorted);
        while($pos = strpos($filledPattern,'?')){
            $filledPattern = substr($filledPattern,0,$pos)
                .$val
                .substr($filledPattern,$pos+1);
            $val = next($sorted);
        }
        
        return $filledPattern;
    }



}