2016-02-01 22:09:35 +00:00
|
|
|
<?php
|
|
|
|
/*************************************************/
|
|
|
|
/* Classe de gestion des routes (URL/ressources) */
|
|
|
|
/*************************************************/
|
|
|
|
|
2016-10-18 14:03:03 +00:00
|
|
|
namespace router\core;
|
2016-02-01 22:09:35 +00:00
|
|
|
|
|
|
|
class Router{
|
|
|
|
// ATTRIBUTS
|
|
|
|
private $url;
|
|
|
|
private $routes;
|
|
|
|
|
|
|
|
/* Initialise le routeur
|
|
|
|
*
|
|
|
|
* @url<String> l'URL de la page courante
|
|
|
|
*
|
|
|
|
* @return this<Router> Retour de l'instance courante
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
public function __construct($url){
|
2018-02-07 13:50:36 +00:00
|
|
|
// Format URI (ne doit pas avoir le premier '/')
|
|
|
|
if( preg_match("@^/@", $url) )
|
|
|
|
$url = substr($url, 1);
|
|
|
|
|
2016-02-01 22:09:35 +00:00
|
|
|
$this->url = $url;
|
|
|
|
|
|
|
|
// On initialise les routes
|
2016-07-04 13:45:29 +00:00
|
|
|
$this->routes = [
|
|
|
|
'GET' => [],
|
|
|
|
'POST' => []
|
|
|
|
];
|
2016-02-01 22:09:35 +00:00
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Ajoute une route GET
|
|
|
|
*
|
|
|
|
* @pattern<String> le format de l'URL associe
|
|
|
|
* @callback<Function> function a appeler si l'URL correspond
|
|
|
|
*
|
|
|
|
* @return this<Router> Retour de l'instance courante
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
public function get($pattern, $callback){
|
|
|
|
array_push(
|
|
|
|
$this->routes['GET'],
|
|
|
|
new Route($pattern, $callback)
|
|
|
|
);
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/* Ajoute une route POST
|
|
|
|
*
|
|
|
|
* @pattern<String> le format de l'URL associe
|
|
|
|
* @callback<Function> function a appeler si l'URL correspond
|
|
|
|
*
|
|
|
|
* @return this<Router> Retour de l'instance courante
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
public function post($pattern, $callback){
|
|
|
|
array_push(
|
|
|
|
$this->routes['POST'],
|
|
|
|
new Route($pattern, $callback)
|
|
|
|
);
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
/* Demarre le routeur
|
|
|
|
*
|
|
|
|
* @return this Retour de l'instance courante
|
|
|
|
*
|
|
|
|
*/
|
|
|
|
public function run(){
|
|
|
|
$httpMethod = $_SERVER['REQUEST_METHOD'];
|
|
|
|
|
|
|
|
// Si aucune route pour la methode courante -> false
|
|
|
|
if( count($this->routes[$httpMethod]) <= 0 )
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Pour chaque route
|
|
|
|
foreach($this->routes[$httpMethod] as $route){
|
|
|
|
// Si la route match
|
|
|
|
if( $route->match($this->url) )
|
|
|
|
return $route->call(); // On l'amorce
|
|
|
|
}
|
|
|
|
|
|
|
|
// Retourne false si erreur
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-07-04 13:45:29 +00:00
|
|
|
?>
|