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 |
|
ed1f74
|
23 |
$controller_object = $this->getObject($controller); |
f6df29
|
24 |
|
1e5093
|
25 |
$args = $this->getActionArguments($controller, $action, $params); |
9aeb12
|
26 |
|
1e5093
|
27 |
$controller_object->$action(...$args); |
9aeb12
|
28 |
} |
F |
29 |
|
1e5093
|
30 |
private function getActionArguments(string $controller, string $action, array $params = []): array { |
F |
31 |
$args = []; |
9aeb12
|
32 |
$method = new ReflectionMethod($controller, $action); |
F |
33 |
foreach($method->getParameters() as $parameter) { |
1e5093
|
34 |
|
9aeb12
|
35 |
$name = $parameter->getName(); |
1e5093
|
36 |
$args[$name] = $params[$name]; |
9aeb12
|
37 |
} |
1e5093
|
38 |
|
F |
39 |
return($args); |
f6df29
|
40 |
} |
5ea733
|
41 |
|
F |
42 |
private function getControllerName(array $params): string { |
|
43 |
$controller = $params["controller"]; |
|
44 |
$controller = str_replace("-", "", ucwords(strtolower($controller), "-")); |
|
45 |
$namespace = "App\Controllers"; |
0fc0f1
|
46 |
|
F |
47 |
if(array_key_exists("namespace", $params)) { |
|
48 |
$namespace .= "\\" . $params["namespace"]; |
|
49 |
} |
|
50 |
|
5ea733
|
51 |
return $namespace . "\\" . $controller; |
F |
52 |
|
|
53 |
} |
ed1f74
|
54 |
|
F |
55 |
private function getObject(string $class_name):object { |
|
56 |
$reflector = new ReflectionClass($class_name); |
|
57 |
$contructor = $reflector->getConstructor(); |
|
58 |
|
|
59 |
$dependencies = []; |
|
60 |
|
|
61 |
if($contructor === null) { |
|
62 |
return new $class_name(); |
|
63 |
} |
|
64 |
|
|
65 |
foreach($contructor->getParameters() as $param) { |
|
66 |
$type = (string) $param->getType(); |
|
67 |
$dependencies[] = $this->getObject($type); |
|
68 |
} |
|
69 |
|
|
70 |
return new $class_name(...$dependencies); |
|
71 |
} |
bb3f24
|
72 |
} |