From a319f3a419790925bed539ba141038c72a83e70f Mon Sep 17 00:00:00 2001 From: Daniel Weipert Date: Mon, 10 Jan 2022 20:29:04 +0100 Subject: Initial commit --- src/Router.php | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/Router.php (limited to 'src/Router.php') diff --git a/src/Router.php b/src/Router.php new file mode 100644 index 0000000..377c00b --- /dev/null +++ b/src/Router.php @@ -0,0 +1,70 @@ + [ + '/' => [Home::class, 'index'], + ], + + 'POST' => [ + '/card/add' => [Card::class, 'add'], + ], + ]; + + /** + * Router constructor. + */ + public function __construct() + { + $request = Request::createFromGlobals(); + $response = new Response(); + + $method = $request->getMethod(); + $path = $request->getPathInfo(); + + // if the route is defined + if (isset($this->routes[$method][$path])) { + try { + // run controller function + $content = call_user_func($this->routes[$method][$path], $request); + + // set response to new response + if ($content instanceof Response) { + $response = $content; + } + + // set content directly otherwise + else { + $response->setContent($content); + } + } + + // catch any errors + catch (AppException $exception) { + $response->setStatusCode($exception->getCode()); + $response->setContent($exception->getMessage()); + } catch (\Exception $exception) { + $response->setStatusCode(Response::HTTP_BAD_REQUEST); + $response->setContent($exception->getMessage()); + } + } + + // route is not defined + else { + $response->setStatusCode(Response::HTTP_NOT_FOUND); + $response->setContent('Not Found'); + } + + $response->send(); + } +} + -- cgit v1.2.3