-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
269 lines (229 loc) · 8.04 KB
/
Copy pathRouter.php
File metadata and controls
269 lines (229 loc) · 8.04 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace Neos;
/**
* Description of router
*
* @author Bill
*/
class Router
{
private $url = '';
private $http = '';
private $base = '';
private $request = '';
private $routers = [];
private $params = [];
private $all = [];
private $method = 'GET';
private $defaultController = 'Access';
private $defaultAction = 'pageNotFound';
static $node = null;
function __construct($routers = [], $request = null, $url = null)
{
if ($request !== null)
define('_RQST', $request);
if ($url !== null)
define('_URL', $url);
$this->routers = $routers;
$this->method = $this->requestMethod();
$this->mount();
}
/**
* Singleton instance
*
*/
static function this()
{
if(is_object(static::$node)) return static::$node;
//else...
list($routers, $request, $url) = array_merge(func_get_args(), [null, null, null]);
return static::$node = new static($routers, $request, $url);
}
/**
* Run controller by user request
*
*/
function run()
{
$res = $this->resolve();
$ctrl = isset($res['controller']) && $res['controller'] !== null ? $res['controller'] : $this->defaultController;
$action = isset($res['action']) && $res['action'] !== null ? $res['action'] : $this->defaultAction;
//Name format to Controller namespace
$tmp = explode('\\', str_replace('/', '\\', $ctrl));
$ctrl = '\\Controller';
foreach($tmp as $tmp1){
$ctrl .= '\\'.ucfirst($tmp1);
}
//instantiate the controller
$controller = new $ctrl(['params' => $res['params'], 'request' => $this->request]);
$this->params = $res['params'];
if (method_exists($controller, $action))
return $controller->$action();
else
return $controller->{static::$defaultAction}();
}
/**
* Insert routers
*
*/
function respond($method = 'all', $request = '', $controller = 'home', $action = 'main')
{
$method = strtoupper(trim($method));
if ($method == 'ALL')
$this->all[] = ['request' => trim($request, '/'), 'controller' => $controller, 'action' => $action];
else {
foreach (explode('|', $method) as $mtd) {
$this->routers[$mtd][] = ['request' => trim($request, '/'), 'controller' => $controller, 'action' => $action];
}
}
return $this;
}
/**
* Resolve
*
*/
function resolve()
{
//first: serach in ALL
$route = $this->searchRouter($this->all);
//now: search for access method
if ($route === false && isset($this->routers[$this->method])) {
$route = $this->searchRouter($this->routers[$this->method]);
}
//not match...
if ($route === false) {
$route['controller'] = $route['action'] = $route['params'] = null;
} elseif (is_callable($route['controller'])) {
//call the handling function with the URL parameters
$route = call_user_func_array($route['controller'], $route['params']);
} elseif (strpos($route['controller'], '::') !== false){
$a = explode('::', $route['controller']);
$route['controller'] = isset($a[0]) ? $a[0] : null;
$route['action'] = isset($a[1]) ? $a[1] : null;
}
//out with decoded router OR false
return $route;
}
//Gets
function getUrl()
{
return $this->url;
}
function getHttp()
{
return $this->http;
}
function getBase()
{
return $this->base;
}
function getRequest()
{
return $this->request;
}
function getRouters()
{
return $this->routers;
}
function getAll()
{
return $this->all;
}
function getMethod()
{
return $this->method;
}
/**
* Mount
*/
private function mount()
{
//Detect SSL access
if (!isset($_SERVER['SERVER_PORT']))
$_SERVER['SERVER_PORT'] = 80;
$http = (isset($_SERVER['HTTPS']) && ($_SERVER["HTTPS"] == "on" || $_SERVER["HTTPS"] == 1 || $_SERVER['SERVER_PORT'] == 443)) ? 'https://' : 'http://';
//What's base??!
$base = isset($_SERVER['PHAR_SCRIPT_NAME']) ? dirname($_SERVER['PHAR_SCRIPT_NAME']) : rtrim(str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']), ' /');
if ($_SERVER['SERVER_PORT'] != 80)
$base .= ':' . $_SERVER['SERVER_PORT'];
//URL & REQST Constants:
defined('_RQST') || define('_RQST', urldecode(isset($_SERVER['REQUEST_URI']) ? urldecode(trim(str_replace($base, '', trim($_SERVER['REQUEST_URI'])), ' /')) : ''));
defined('_URL') || define('_URL', isset($_SERVER['SERVER_NAME']) ? $http . $_SERVER['SERVER_NAME'] . $base . '/' : '');
$this->request = _RQST;
$this->url = _URL;
$this->base = $base;
$this->http = $http;
}
/**
* Search for valide router
*
* @params
*/
private function searchRouter($routes)
{
foreach ($routes as $route) {
if (!preg_match_all('#^' . $route['request'] . '$#', $this->request, $matches, PREG_OFFSET_CAPTURE))
continue;
// Rework matches to only contain the matches, not the orig string
$matches = array_slice($matches, 1);
// Extract the matched URL parameters (and only the parameters)
$params = array_map(function ($match, $index) use ($matches) {
// We have a following parameter: take the substring from the current param position until the next one's position (thank you PREG_OFFSET_CAPTURE)
if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) {
return trim(substr($match[0][0], 0, $matches[$index + 1][0][1] - $match[0][1]), '/');
} // We have no following parameters: return the whole lot
else {
return (isset($match[0][0]) ? trim($match[0][0], '/') : null);
}
}, $matches, array_keys($matches));
$route['params'] = $params;
return $route;
}
//not exists ...
return false;
}
/**
* Get all request headers
* @return array The request headers
*/
private function requestHeaders()
{
// getallheaders available, use that
if (function_exists('getallheaders')) {
return getallheaders();
}
// getallheaders not available: manually extract 'm
$headers = array();
foreach ($_SERVER as $name => $value) {
if ((substr($name, 0, 5) == 'HTTP_') || ($name == 'CONTENT_TYPE') || ($name == 'CONTENT_LENGTH')) {
$headers[str_replace(array(' ', 'Http'), array('-', 'HTTP'), ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
/**
* Get the request method used, taking overrides into account
* @return string The Request method to handle
*/
private function requestMethod()
{
// Take the method as found in $_SERVER
$method = $_SERVER['REQUEST_METHOD'];
if ($_SERVER['REQUEST_METHOD'] == 'HEAD') {
ob_start();
$method = 'GET';
} // If it's a POST request, check for a method override header
elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
$headers = $this->requestHeaders();
if (isset($headers['X-HTTP-Method-Override']) && in_array($headers['X-HTTP-Method-Override'], array('PUT', 'DELETE', 'PATCH'))) {
$method = $headers['X-HTTP-Method-Override'];
}
}
return $method;
}
}