Permet de définir la base de l'url dans le routeur
This commit is contained in:
@@ -10,40 +10,49 @@ use Silex\DI\DI;
|
||||
class Router
|
||||
{
|
||||
|
||||
private string $url;
|
||||
private string $url;
|
||||
|
||||
/**
|
||||
* @var Route[]
|
||||
*/
|
||||
private array $routes = [];
|
||||
/**
|
||||
* @var Route[]
|
||||
*/
|
||||
private array $routes = [];
|
||||
|
||||
public function __construct(string $url)
|
||||
{
|
||||
$this->url = trim($url, '/');;
|
||||
}
|
||||
public function __construct(string $url)
|
||||
{
|
||||
$this->url = trim($url, '/');;
|
||||
}
|
||||
|
||||
public function get(string $path, callable $callable): self
|
||||
{
|
||||
return $this->addRoute('GET', $path, $callable);
|
||||
}
|
||||
public function setBasePath(string $basePath)
|
||||
{
|
||||
$pos = strpos($this->url, $basePath);
|
||||
if ($pos !== false) {
|
||||
$this->url = substr($this->url, $pos + strlen($basePath));
|
||||
}
|
||||
var_dump($this->url);
|
||||
}
|
||||
|
||||
private function addRoute(string $method, string $path, $callable): self
|
||||
{
|
||||
$route = new Route($path, $callable);
|
||||
$this->routes[$method][] = $route;
|
||||
return $this;
|
||||
}
|
||||
public function get(string $path, callable $callable): self
|
||||
{
|
||||
return $this->addRoute('GET', $path, $callable);
|
||||
}
|
||||
|
||||
public function run(DI $di): HttpResponse
|
||||
{
|
||||
if (!isset($this->routes[$_SERVER['REQUEST_METHOD']])) {
|
||||
throw new RouteNotFoundException('Unknown HTTP method');
|
||||
}
|
||||
foreach ($this->routes[$_SERVER['REQUEST_METHOD']] as $route) {
|
||||
if ($route->matches($this->url)) {
|
||||
return $route->call($di);
|
||||
}
|
||||
}
|
||||
throw new RouteNotFoundException('No matching routes');
|
||||
}
|
||||
private function addRoute(string $method, string $path, $callable): self
|
||||
{
|
||||
$route = new Route($path, $callable);
|
||||
$this->routes[$method][] = $route;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function run(DI $di): HttpResponse
|
||||
{
|
||||
if (!isset($this->routes[$_SERVER['REQUEST_METHOD']])) {
|
||||
throw new RouteNotFoundException('Unknown HTTP method');
|
||||
}
|
||||
foreach ($this->routes[$_SERVER['REQUEST_METHOD']] as $route) {
|
||||
if ($route->matches($this->url)) {
|
||||
return $route->call($di);
|
||||
}
|
||||
}
|
||||
throw new RouteNotFoundException('No matching routes');
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user