corso https://vola.udemy.com/course/php-mvc-from-scratch/learn/lecture/40931984#overview
filippo.bertilotti
2024-05-14 7baa142488879722eaffe263ddc064072f4df973
commit | author | age
bb3f24 1 <?php
F 2
3 namespace Framework;
4
9aeb12 5 use ReflectionMethod;
7baa14 6 use ReflectionClass;
9aeb12 7
bb3f24 8 class Dispatcher {
F 9     public function __construct(private Router $router) { }
f6df29 10
F 11     public function handle(string $path) {
12         $params = $this->router->match($path);
13
14         if($params === false) {
15             exit("No routes matched");
16         }
17
18         $controller = "App\Controllers\\" . ucwords($params["controller"]);
19         $action = $params["action"];
20
5ea733 21         $controller = $this->getControllerName($params);
F 22
7baa14 23         $reflector = new ReflectionClass($controller);
F 24         $contructor = $reflector->getConstructor();
25         
26         if($contructor !== null) {
27             foreach($contructor->getParameters() as $param) {
28                 $type = (string) $param->getType();
29                 $dependencies[] = new $type;
30             }
31         }
32         $controller_object = new $controller(...$dependencies);
f6df29 33
1e5093 34         $args = $this->getActionArguments($controller, $action, $params);
9aeb12 35
1e5093 36         $controller_object->$action(...$args);
9aeb12 37     }
F 38
1e5093 39     private function getActionArguments(string $controller, string $action, array $params = []): array {
F 40         $args = [];
9aeb12 41         $method = new ReflectionMethod($controller, $action);
F 42         foreach($method->getParameters() as $parameter) {
1e5093 43
9aeb12 44             $name = $parameter->getName();
1e5093 45             $args[$name] = $params[$name];
9aeb12 46         }
1e5093 47
F 48         return($args);
f6df29 49     }
5ea733 50
F 51     private function getControllerName(array $params): string {
52         $controller = $params["controller"];
53         $controller = str_replace("-", "", ucwords(strtolower($controller), "-"));
54         $namespace = "App\Controllers";
0fc0f1 55
F 56         if(array_key_exists("namespace", $params)) {
57             $namespace .= "\\" . $params["namespace"];
58         }
59
5ea733 60         return $namespace . "\\" . $controller;
F 61
62     }
bb3f24 63 }