-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRouter.php
94 lines (79 loc) · 2.26 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
namespace hussainalihussain\phpmvclaravelclonecore;
use hussainalihussain\phpmvclaravelclonecore\exceptions\ForbiddenMethodCalled;
use hussainalihussain\phpmvclaravelclonecore\exceptions\NotFoundException;
class Router
{
const METHOD_GET = 'get';
const METHOD_POST = 'post';
public $routes = [];
/**
* @var Request
*/
public $request;
/**
* @param Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* @param string $url
* @param $callback
* @return void
*/
public function get(string $url, $callback)
{
$this->routes[self::METHOD_GET][$url] = $callback;
}
/**
* @param string $url
* @param $callback
* @return void
*/
public function post(string $url, $callback)
{
$this->routes[self::METHOD_POST][$url] = $callback;
}
/**
* @return array|false|mixed|string|string[]
* @throws NotFoundException
* @throws ForbiddenMethodCalled
*/
public function resolve()
{
$method = $this->request->method();
$path = $this->request->path();
$callback = $this->routes[$method][$path] ?? null;
if(!$callback)
{
$anotherMethod = $method == 'get' ? 'post' : 'get';
$anotherCallback = $this->routes[$anotherMethod][$path] ?? null;
if($anotherCallback)
{
throw new ForbiddenMethodCalled();
}
throw new NotFoundException();
}
if(is_string($callback))
{
return Application::$app->view->renderView($callback);
}
if(is_array($callback))
{
$callback[0] = new $callback[0]();
Application::$app->controller = $callback[0];
Application::$app->controller->action = $callback[1];
$this->runMiddlewares();
}
return call_user_func($callback, Application::$app->request, Application::$app->response);
}
public function runMiddlewares()
{
foreach (Application::$app->controller->getMiddlewares() as $middleware)
{
$middleware->execute();
}
}
}