diff --git a/public/index.php b/public/index.php index 7d9625e..ca12d70 100644 --- a/public/index.php +++ b/public/index.php @@ -1,11 +1,15 @@ register(); -// TODO router $controller = new \Silex\Controller\UserController(); -$controller->index(new \Silex\DI\DI())->render(__DIR__ . '/../' . VIEW_PATH); +$router = new Router($_SERVER['REQUEST_URI']); +$router->get('/^$/', [$controller, 'index']); +//$router->get('/^inscription$/', [$controller, 'connexion']); +$router->run(new \Silex\DI\DI())->render(__DIR__ . '/../' . VIEW_PATH); diff --git a/src/Silex/Router/Route.php b/src/Silex/Router/Route.php new file mode 100644 index 0000000..2278e61 --- /dev/null +++ b/src/Silex/Router/Route.php @@ -0,0 +1,37 @@ +path = $path; + $this->callable = $callable; + } + + public function matches(string $url): bool + { + return preg_match($this->path, $url, $this->matches) === 1; + } + + public function call(DI $di): HttpResponse + { + return call_user_func_array($this->callable, [$di, $this->matches]); + } +} diff --git a/src/Silex/Router/RouteNotFoundException.php b/src/Silex/Router/RouteNotFoundException.php new file mode 100644 index 0000000..e6c8f9f --- /dev/null +++ b/src/Silex/Router/RouteNotFoundException.php @@ -0,0 +1,20 @@ +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'); + } +}