<?php
namespace elanpl\L3;
class Router{
protected $routes;
protected $parsedParameters;
protected $depth;
protected $routeNameIndex;
public $RouteInfo;
public function __construct($routing)
{
$this->routes = array();
$this->routeNameIndex = array();
$routing->set($this);
}
public function add($Method, $Path, $Result, $Name = ''){
$this->routes[] = new RouteInfo($Method, $Path, $Result, $Name);
if(isset($Name)&&$Name!='') $this->routeNameIndex[$Name] = &$this->routes[count($this->routes)-1];
return $this;
}
public function get($Path, $Result, $Name = ''){
return $this->add('GET', $Path, $Result, $Name);
}
public function post($Path, $Result, $Name = ''){
return $this->add('POST', $Path, $Result, $Name);
}
public function put($Path, $Result, $Name = ''){
return $this->add('PUT', $Path, $Result, $Name);
}
public function patch($Path, $Result, $Name = ''){
return $this->add('PATCH', $Path, $Result, $Name);
}
public function delete($Path, $Result, $Name = ''){
return $this->add('DELETE', $Path, $Result, $Name);
}
public function any($Path, $Result, $Name = ''){
return $this->add('ANY', $Path, $Result, $Name);
}
public function AddBeforeAction($event_handler){
$this->routes[count($this->routes)-1]->AddBeforeAction($event_handler);
return $this;
}
public function AddAfterAction($event_handler){
$this->routes[count($this->routes)-1]->AddAfterAction($event_handler);
return $this;
}
public function AddAfterResult($event_handler){
$this->routes[count($this->routes)-1]->AddAfterAction($event_handler);
return $this;
}
public function match($Request){
$auri = explode('/', trim($Request->Path, "/ \t\n\r\0\x0B"));
$curi = count($auri);
foreach ($this->routes as $routeInfo) {
$route = $routeInfo->Path;
$method = $routeInfo->Method;
if($method=='ANY' || strpos($Request->Method,$method)!==false){
$aroute = explode('/', trim($route, "/ \t\n\r\0\x0B"));
if($curi==count($aroute)){
$matchResult = true;
for($i = 0; $i<$curi; $i++){
$pathPartName = trim($aroute[$i],'{}');
if($aroute[$i]==$pathPartName){
if($auri[$i]!=$pathPartName){
$matchResult = false;
break;
}
}
else{
$value = $auri[$i];
$valueKey = explode(':', $pathPartName);
if(isset($valueKey[1]) && $valueKey[1]=='int'){
$value = intval($value);
}
$this->parsedParameters[$valueKey[0]] = $value;
}
}
if($matchResult){
$this->depth = $curi;
$this->RouteInfo = $routeInfo;