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