-
Notifications
You must be signed in to change notification settings - Fork 0
/
Router.php
76 lines (67 loc) · 1.89 KB
/
Router.php
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
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
/**
* User: grnspc
* Date: 7/7/2020
* Time: 10:01 AM
*/
namespace grnspc\phpmvc;
use grnspc\phpmvc\exception\NotFoundException;
/**
* Class Router
*
* @author Nathan Robinson <[email protected]>
* @package grnspc\mvc
*/
class Router
{
private Request $request;
private Response $response;
private array $routeMap = [];
public function __construct(Request $request, Response $response)
{
$this->request = $request;
$this->response = $response;
}
public function get(string $url, $callback)
{
$this->routeMap['get'][$url] = $callback;
}
public function post(string $url, $callback)
{
$this->routeMap['post'][$url] = $callback;
}
public function resolve()
{
$method = $this->request->getMethod();
$url = $this->request->getUrl();
$callback = $this->routeMap[$method][$url] ?? false;
if (!$callback) {
throw new NotFoundException();
}
if (is_string($callback)) {
return $this->renderView($callback);
}
if (is_array($callback)) {
/**
* @var $controller \grnspc\phpmvc\Controller
*/
$controller = new $callback[0];
$controller->action = $callback[1];
Application::$app->controller = $controller;
$middlewares = $controller->getMiddlewares();
foreach ($middlewares as $middleware) {
$middleware->execute();
}
$callback[0] = $controller;
}
return call_user_func($callback, $this->request, $this->response);
}
public function renderView($view, $params = [])
{
return Application::$app->view->renderView($view, $params);
}
public function renderViewOnly($view, $params = [])
{
return Application::$app->view->renderViewOnly($view, $params);
}
}