From 0b87390cf225ee1053f1d5986900784d39110568 Mon Sep 17 00:00:00 2001
From: filippo.bertilotti <filippobertilotti@gmail.com>
Date: Tue, 28 May 2024 12:43:27 +0200
Subject: [PATCH] creazione di piĆ¹ viewer controllers per renderizzare diversi tipi di views (parte 151)

---
 src/Framework/Dispatcher.php |   26 +++++++++++++++++++++-----
 1 files changed, 21 insertions(+), 5 deletions(-)

diff --git a/src/Framework/Dispatcher.php b/src/Framework/Dispatcher.php
index 95591ca..06cf395 100644
--- a/src/Framework/Dispatcher.php
+++ b/src/Framework/Dispatcher.php
@@ -2,16 +2,21 @@
 
 namespace Framework;
 
+use Framework\Exceptions\PageNotFoundException;
 use ReflectionMethod;
+use UnexpectedValueException;
 
 class Dispatcher {
-    public function __construct(private Router $router) { }
+    public function __construct(private Router $router,
+                                private Container $container) { }
 
-    public function handle(string $path) {
-        $params = $this->router->match($path);
+    public function handle(Request $request) {
+
+        $path = $this->getPath($request->uri);
+        $params = $this->router->match($path, $request->method);
 
         if($params === false) {
-            exit("No routes matched");
+            throw new PageNotFoundException("No route matched for '$path' with method '$request->method'");
         }
 
         $controller = "App\Controllers\\" . ucwords($params["controller"]);
@@ -19,7 +24,10 @@
 
         $controller = $this->getControllerName($params);
 
-        $controller_object = new $controller;
+        $controller_object = $this->container->get($controller);
+        
+        $controller_object->setRequest($request);
+        $controller_object->setViewer($this->container->get(PHPTemplateViewer::class));
 
         $args = $this->getActionArguments($controller, $action, $params);
 
@@ -50,4 +58,12 @@
         return $namespace . "\\" . $controller;
 
     }
+
+    public function getPath(string $uri): string {
+        $path = parse_url($uri, PHP_URL_PATH);
+        if ($path === false) {
+        throw new UnexpectedValueException("Malformed URL: {$uri}");
+        }
+        return $path;
+    }
 }
\ No newline at end of file

--
Gitblit v1.8.0