1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| <?php
namespace Library;
class Router{
protected $routes = array();
const NO_ROUTE = 1;
public function addRoute(Route $route){
if (!in_array($route, $this->routes)){
$this->routes[] = $route;
}
}
public function getRoute($url){
foreach ($this->routes as $route){
// Si la route correspond à l'URL.
if (($varsValues = $route->match($url)) !== false){
// Si elle a des variables.
if ($route->hasVars()){
$varsNames = $route->getVarsNames();
$listVars = array();
// On créé un nouveau tableau clé/valeur.
foreach ($varsValues as $key => $match){
// La première valeur contient entièrement la chaine capturée (voir la doc sur preg_match).
if ($key !== 0){
$listVars[$varsNames[$key - 1]] = $match;
}
}
// On assigne ce tableau de variables à la route.
$route->setVars($listVars);
}
return $route;
}
}
throw new \RuntimeException('Aucune route ne correspond à l\'URL', self::NO_ROUTE);
}
} |
Partager