Route les urls

This commit is contained in:
2022-11-15 09:42:45 +01:00
parent 22127b8702
commit 4d1ef981d2
4 changed files with 112 additions and 2 deletions

View File

@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace Silex\Router;
use Silex\Http\HttpResponse;
use Silex\DI\DI;
class Router
{
private string $url;
/**
* @var Route[]
*/
private array $routes = [];
public function __construct(string $url)
{
$this->url = trim($url, '/');;
}
public function get(string $path, callable $callable): self
{
return $this->addRoute('GET', $path, $callable);
}
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');
}
}