1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace rAPId\Routing; |
4
|
|
|
|
5
|
|
|
use rAPId\Exceptions\InvalidUrlException; |
6
|
|
|
use rAPId\Foundation\Response; |
7
|
|
|
use ReflectionMethod; |
8
|
|
|
|
9
|
|
|
class Router |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @param $url |
13
|
|
|
* |
14
|
|
|
* @return Response |
15
|
|
|
* @throws InvalidUrlException |
16
|
|
|
*/ |
17
|
|
|
public static function resolve($url) { |
18
|
|
|
$route = Route::parse($url); |
19
|
|
|
try { |
20
|
|
|
$controller = $route->getController(); |
21
|
|
|
$action = $route->getAction(); |
22
|
|
|
$args = self::getMethodSpecificArgs($route); |
23
|
|
|
|
24
|
|
|
$controller = new $controller(); |
25
|
|
|
$response = $controller->{$action}(...$args); |
26
|
|
|
} catch (\Exception $ex) { |
27
|
|
|
throw new InvalidUrlException("Call Failed to [$url]. Make sure your DEFAULT_CONTROLLER is set", $ex->getCode(), $ex); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
return new Response($response); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Returns an array of arguments |
35
|
|
|
* in the order that they are to be called in the controller method |
36
|
|
|
* |
37
|
|
|
* @param Route $route |
38
|
|
|
* |
39
|
|
|
* @return array $args |
40
|
|
|
*/ |
41
|
|
|
private static function getMethodSpecificArgs(Route $route) { |
42
|
|
|
|
43
|
|
|
$parameters = self::getControllerMethodParameters($route->getController(), $route->getAction()); |
44
|
|
|
$route_args = $route->getArgs(); |
45
|
|
|
$request_args = self::getRequestArgs(); |
46
|
|
|
|
47
|
|
|
$ordered_arguments = []; |
48
|
|
|
foreach ($parameters as $parameter) { |
49
|
|
|
|
50
|
|
|
$value = array_get($request_args, $parameter->name); |
51
|
|
|
if (!array_key_exists($parameter->name, $request_args)) { |
52
|
|
|
$value = array_shift($route_args); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
$ordered_arguments[] = $value; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return $ordered_arguments; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param string $controller |
63
|
|
|
* @param string $method |
64
|
|
|
* |
65
|
|
|
* @return \ReflectionParameter[] |
66
|
|
|
*/ |
67
|
|
|
private static function getControllerMethodParameters($controller, $method) { |
68
|
|
|
$reflection_method = new ReflectionMethod($controller, $method); |
69
|
|
|
|
70
|
|
|
return $reflection_method->getParameters(); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @return array |
75
|
|
|
*/ |
76
|
|
|
private static function getRequestArgs() { |
77
|
|
|
return $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET; |
78
|
|
|
} |
79
|
|
|
} |