|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Win\Request; |
|
4
|
|
|
|
|
5
|
|
|
use Win\Application; |
|
6
|
|
|
use Win\Response\Response; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Rota de URL |
|
10
|
|
|
* |
|
11
|
|
|
* Redireciona a requisição para um "Controller@action". |
|
12
|
|
|
* @see "/app/config/routes.php" |
|
13
|
|
|
*/ |
|
14
|
|
|
class Router |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var string[] */ |
|
17
|
|
|
protected static $routes = []; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Adiciona as rotas |
|
21
|
|
|
* @param string $namespace |
|
22
|
|
|
* @param string[] $routes |
|
23
|
|
|
*/ |
|
24
|
|
|
public static function addRoutes($namespace, $routes) |
|
25
|
|
|
{ |
|
26
|
|
|
foreach ($routes as $request => $destination) { |
|
27
|
|
|
static::$routes[$request] = $namespace . $destination; |
|
28
|
|
|
} |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Percorre todas as rotas e retorna o destino final |
|
33
|
|
|
* @return mixed[] Destino |
|
34
|
|
|
* @example return [Controller, action, [..$args]] |
|
35
|
|
|
*/ |
|
36
|
|
|
public static function getDestination() |
|
37
|
|
|
{ |
|
38
|
|
|
$url = Url::instance(); |
|
39
|
|
|
$matches = []; |
|
40
|
|
|
|
|
41
|
|
|
foreach (static::$routes as $request => $destination) { |
|
42
|
|
|
$pattern = '@^' . $url->format($request) . '$@'; |
|
43
|
|
|
$match = 1 == preg_match($pattern, $url->getUrl(), $matches); |
|
44
|
|
|
if ($match) { |
|
45
|
|
|
$args = array_splice($matches, 1); |
|
46
|
|
|
$target = array_pad(explode('@', $destination), 2, ''); |
|
47
|
|
|
$target[] = $args; |
|
48
|
|
|
|
|
49
|
|
|
return $target; |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
throw new HttpException('Route not found', 404); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* Processa e envia uma resposta baseada no destino [Controller, action, [...args]] |
|
58
|
|
|
* @param array $destination |
|
59
|
|
|
*/ |
|
60
|
|
|
public static function process($destination) |
|
61
|
|
|
{ |
|
62
|
|
|
$class = $destination[0]; |
|
63
|
|
|
$action = rtrim($destination[1], '@') ?? ''; |
|
64
|
|
|
$args = $destination[2] ?? []; |
|
65
|
|
|
|
|
66
|
|
|
if (!class_exists($class)) { |
|
67
|
|
|
throw new HttpException("Controller '{$class}' not found", 404); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
$controller = new $class(); |
|
71
|
|
|
$controller->app = Application::app(); |
|
72
|
|
|
$controller->app->controller = $controller; |
|
73
|
|
|
if (!method_exists($controller, $action)) { |
|
74
|
|
|
throw new HttpException("Action '{$action}' not found in '{$class}'", 404); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
$response = $controller->$action(...$args); |
|
78
|
|
|
echo ($response instanceof Response) ? $response->respond() : $response; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|