NxTIC/router/Route.php

63 lines
1.2 KiB
PHP
Raw Normal View History

<?php
/**************************************/
/* Classe de gestion de route (match) */
/**************************************/
namespace router;
class Route{
// ATTRIBUTS
private $pattern;
private $callback;
private $matches = array();
/* Initialise la route
*
* @pattern<String> Pattern correspondant a la route
* @callback<Function> Fonction de callback de la route
*
* @return this<Route> Retour de l'instance courante
*
*/
public function __construct($pattern, $callback){
// On enregistre la fonction de callback
$this->callback = $callback;
// On formatte le pattern en regexp
$this->pattern = '#^'.$pattern.'$#';
return $this;
}
/* Verifie si l'URL correspond a la route
*
* @url<String> URL pour laquelle on veut verifier
*
* @return match<Boolean> TRUE si match sinon FAUX
*
*/
public function match($url){
// Si ne match pas -> FALSE
if( !preg_match($this->pattern, $url, $matches) )
return false;
// On supprime le premier match global
array_shift($matches);
$this->matches = $matches;
return true;
}
/* Amorcage de la fonction de callback
*
*/
public function call(){
return call_user_func($this->callback, $this->matches);
}
}
?>