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