forked from afgprogrammer/PHP-MVC-REST-API
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
242 lines (203 loc) · 5.76 KB
/
Router.php
File metadata and controls
242 lines (203 loc) · 5.76 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
<?php
/**
*
* This file is part of mvc-rest-api for PHP.
*
*/
namespace Router;
/**
* Class Router For Handel Router
*
* @author Mohammad Rahmani <rto1680@gmail.com>
*
* @package Router
*/
class Router {
/**
* route list.
*
* @var array
*/
private $router = [];
/**
* match route list.
*
* @var array
*/
private $matchRouter = [];
/**
* request url.
*
* @var string
*/
private $url;
/**
* request http method.
*
* @var string
*/
private $method;
/**
* param list for route pattern
*
* @var array
*/
private $params = [];
/**
* Response Class
*/
private $response;
/**
* construct
*/
public function __construct(string $url, string $method) {
$this->url = rtrim($url, '/');
$this->method = $method;
// get response class of $GLOBALS var
$this->response = $GLOBALS['response'];
}
/**
* set get request http method for route
*/
public function get($pattern, $callback) {
$this->addRoute("GET", $pattern, $callback);
}
/**
* set post request http method for route
*/
public function post($pattern, $callback) {
$this->addRoute('POST', $pattern, $callback);
}
/**
* set put request http method for route
*/
public function put($pattern, $callback) {
$this->addRoute('PUT', $pattern, $callback);
}
/**
* set delete request http method for route
*/
public function delete($pattern, $callback) {
$this->addRoute('DELETE', $pattern, $callback);
}
/**
* add route object into router var
*/
public function addRoute($method, $pattern, $callback) {
array_push($this->router, new Route($method, $pattern, $callback));
}
/**
* filter requests by http method
*/
private function getMatchRoutersByRequestMethod() {
foreach ($this->router as $value) {
if (strtoupper($this->method) == $value->getMethod())
array_push($this->matchRouter, $value);
}
}
/**
* filter route patterns by url request
*/
private function getMatchRoutersByPattern($pattern) {
$this->matchRouter = [];
foreach ($pattern as $value) {
if ($this->dispatch(cleanUrl($this->url), $value->getPattern()))
array_push($this->matchRouter, $value);
}
}
/**
* dispatch url and pattern
*/
public function dispatch($uri, $pattern) {
$parsUrl = explode('?', $uri);
$url = $parsUrl[0];
preg_match_all('@:([\w]+)@', $pattern, $params, PREG_PATTERN_ORDER);
$patternAsRegex = preg_replace_callback('@:([\w]+)@', [$this, 'convertPatternToRegex'], $pattern);
if (substr($pattern, -1) === '/' ) {
$patternAsRegex = $patternAsRegex . '?';
}
$patternAsRegex = '@^' . $patternAsRegex . '$@';
// check match request url
if (preg_match($patternAsRegex, $url, $paramsValue)) {
array_shift($paramsValue);
foreach ($params[0] as $key => $value) {
$val = substr($value, 1);
if ($paramsValue[$val]) {
$this->setParams($val, urlencode($paramsValue[$val]));
}
}
return true;
}
return false;
}
/**
* get router
*/
public function getRouter() {
return $this->router;
}
/**
* set param
*/
private function setParams($key, $value) {
$this->params[$key] = $value;
}
/**
* Convert Pattern To Regex
*/
private function convertPatternToRegex($matches) {
$key = str_replace(':', '', $matches[0]);
return '(?P<' . $key . '>[a-zA-Z0-9_\-\.\!\~\*\\\'\(\)\:\@\&\=\$\+,%]+)';
}
/**
* run application
*/
public function run() {
if (!is_array($this->router) || empty($this->router))
throw new Exception('NON-Object Route Set');
$this->getMatchRoutersByRequestMethod();
$this->getMatchRoutersByPattern($this->matchRouter);
if (!$this->matchRouter || empty($this->matchRouter)) {
$this->sendNotFound();
} else {
// call to callback method
if (is_callable($this->matchRouter[0]->getCallback()))
call_user_func($this->matchRouter[0]->getCallback(), $this->params);
else
$this->runController($this->matchRouter[0]->getCallback(), $this->params);
}
}
/**
* run as controller
*/
private function runController($controller, $params) {
$parts = explode('@', $controller);
$file = CONTROLLERS . ucfirst($parts[0]) . '.php';
if (file_exists($file)) {
require_once($file);
// controller class
$controller = 'Controllers' . ucfirst($parts[0]);
if (class_exists($controller))
$controller = new $controller();
else
$this->sendNotFound();
// set function in controller
if (isset($parts[1])) {
$method = $parts[1];
if (!method_exists($controller, $method))
$this->sendNotFound();
} else {
$method = 'index';
}
// call to controller
if (is_callable([$controller, $method]))
return call_user_func([$controller, $method], $params);
else
$this->sendNotFound();
}
}
private function sendNotFound() {
$this->response->sendStatus(404);
$this->response->setContent(['error' => 'Sorry This Route Not Found !', 'status_code' => 404]);
}
}