Permet de définir la base de l'url dans le routeur

This commit is contained in:
2022-11-22 08:12:06 +01:00
parent 4d1ef981d2
commit 9bc53b958f

View File

@@ -10,40 +10,49 @@ use Silex\DI\DI;
class Router class Router
{ {
private string $url; private string $url;
/** /**
* @var Route[] * @var Route[]
*/ */
private array $routes = []; private array $routes = [];
public function __construct(string $url) public function __construct(string $url)
{ {
$this->url = trim($url, '/');; $this->url = trim($url, '/');;
} }
public function get(string $path, callable $callable): self public function setBasePath(string $basePath)
{ {
return $this->addRoute('GET', $path, $callable); $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 public function get(string $path, callable $callable): self
{ {
$route = new Route($path, $callable); return $this->addRoute('GET', $path, $callable);
$this->routes[$method][] = $route; }
return $this;
}
public function run(DI $di): HttpResponse private function addRoute(string $method, string $path, $callable): self
{ {
if (!isset($this->routes[$_SERVER['REQUEST_METHOD']])) { $route = new Route($path, $callable);
throw new RouteNotFoundException('Unknown HTTP method'); $this->routes[$method][] = $route;
} return $this;
foreach ($this->routes[$_SERVER['REQUEST_METHOD']] as $route) { }
if ($route->matches($this->url)) {
return $route->call($di); public function run(DI $di): HttpResponse
} {
} if (!isset($this->routes[$_SERVER['REQUEST_METHOD']])) {
throw new RouteNotFoundException('No matching routes'); 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');
}
} }