summaryrefslogtreecommitdiff
path: root/src/Router.php
diff options
context:
space:
mode:
authorDaniel Weipert <git@mail.dweipert.de>2025-08-10 10:46:41 +0200
committerDaniel Weipert <git@mail.dweipert.de>2025-08-10 10:46:41 +0200
commitc14579871fa1241713128a2d0d5514af004e3371 (patch)
tree6b28c42958650d94c9aa1947a0b5c32eb869d89f /src/Router.php
initial commit
Diffstat (limited to 'src/Router.php')
-rw-r--r--src/Router.php52
1 files changed, 52 insertions, 0 deletions
diff --git a/src/Router.php b/src/Router.php
new file mode 100644
index 0000000..deb852e
--- /dev/null
+++ b/src/Router.php
@@ -0,0 +1,52 @@
+<?php
+
+namespace App;
+
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Component\Routing\Loader\Configurator\RouteConfigurator;
+use Symfony\Component\Routing\Matcher\UrlMatcher;
+use Symfony\Component\Routing\RequestContext;
+use Symfony\Component\Routing\RouteCollection;
+
+class Router
+{
+ use Singleton;
+
+ private RouteCollection $routes;
+ private RouteConfigurator $configurator;
+
+ public function __construct()
+ {
+ $this->routes = new RouteCollection();
+ $this->configurator = new RouteConfigurator($this->routes, $this->routes);
+
+ $this->addRoutes();
+ }
+
+ public function run(): Response
+ {
+ $request = Request::createFromGlobals();
+
+ $context = new RequestContext();
+ $context->fromRequest($request);
+
+ try {
+ $matcher = new UrlMatcher($this->routes, $context);
+ $match = $matcher->matchRequest($request);
+
+ $class = $match["_controller"][0];
+ $method = $match["_controller"][1];
+
+ return (new $class)->$method();
+ } catch (\Exception $exception) {
+ return new Response("500: " . $exception->getMessage(), 500);
+ }
+ }
+
+ private function addRoutes(): void
+ {
+ $routes = include_once(__DIR__ . "/routes.php");
+ $routes($this->configurator);
+ }
+}