summaryrefslogtreecommitdiff
path: root/src/Router.php
diff options
context:
space:
mode:
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();
+ }
+}
+