99 lines
2.3 KiB
PHP
99 lines
2.3 KiB
PHP
<?php
|
|
|
|
/**************************
|
|
* Route *
|
|
* 08-12-2016 *
|
|
***************************
|
|
* Designed & Developed by *
|
|
* xdrm-brackets *
|
|
***************************
|
|
* https://xdrm.io/ *
|
|
**************************/
|
|
|
|
namespace router\core;
|
|
|
|
class Route{
|
|
|
|
/* [1] Attributs
|
|
=========================================================*/
|
|
private $pattern;
|
|
private $controller;
|
|
private $method;
|
|
private $matches;
|
|
|
|
|
|
/* [2] Instanciation de la route
|
|
*
|
|
* @pattern<String> Pattern correspondant a la route
|
|
* @controller<String> Controller de la route
|
|
* @method<String> Methode du controller
|
|
*
|
|
* @return instance<Route> Retour de l'instance courante
|
|
*
|
|
=========================================================*/
|
|
public function __construct($pattern=null, $controller=null, $method=null){
|
|
// Note: all arguments must be verified by 'Router->add' method
|
|
|
|
/* (1) Pattern -> regex format */
|
|
$this->pattern = "/^$pattern$/";
|
|
|
|
/* (2) Controller */
|
|
$this->controller = $controller;
|
|
|
|
/* (3) Controller's method */
|
|
$this->method = $method;
|
|
|
|
/* (4) Initialize matches */
|
|
$this->matches = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
/* [3] Checks if route matches URL
|
|
*
|
|
* @url<String> URL
|
|
*
|
|
* @return matches<Boolean> If matches URL
|
|
*
|
|
=========================================================*/
|
|
public function match($url){
|
|
|
|
/* (1) If doesn't matches @url -> false */
|
|
if( !preg_match($this->pattern, $url, $matches) )
|
|
return false;
|
|
|
|
/* (2) Return only named matches */
|
|
foreach($matches as $name=>$match)
|
|
if( !is_numeric($name) )
|
|
$this->matches[$name] = $match;
|
|
|
|
/* (4) Add complete URL */
|
|
$this->matches['__URL__'] = $url;
|
|
|
|
/* (5) Return status */
|
|
return true;
|
|
}
|
|
|
|
|
|
/* [4] Method call
|
|
*
|
|
* @return response<String> Response
|
|
*
|
|
=========================================================*/
|
|
public function call(){
|
|
/* (1) Instanciate controller */
|
|
$instance = ControllerFactory::getController($this->controller, $this->matches);
|
|
|
|
/* (2) Launch method & catch response */
|
|
$response = call_user_func([$instance, $this->method]);
|
|
|
|
/* (3) Call controller's destructor */
|
|
$instance = null;
|
|
|
|
/* (4) Return response */
|
|
return $response;
|
|
}
|
|
|
|
}
|