summaryrefslogtreecommitdiff
path: root/src/Router.php
diff options
context:
space:
mode:
authorDaniel Weipert <code@drogueronin.de>2022-01-10 20:29:04 +0100
committerDaniel Weipert <code@drogueronin.de>2022-01-10 20:29:04 +0100
commita319f3a419790925bed539ba141038c72a83e70f (patch)
treedfb24183cc693863df733e190dbbc6da93bb82e5 /src/Router.php
Initial commit
Diffstat (limited to 'src/Router.php')
-rw-r--r--src/Router.php70
1 files changed, 70 insertions, 0 deletions
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 @@
+<?php
+
+namespace Elements;
+
+use Elements\Controller\Card;
+use Elements\Controller\Home;
+use Symfony\Component\HttpFoundation\RedirectResponse;
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Response;
+
+class Router
+{
+ private $routes = [
+ 'GET' => [
+ '/' => [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();
+ }
+}
+