Repository navigation
Expand file tree
/
Copy pathRouter.php
More file actions
391 lines (352 loc) · 10.9 KB
/
Copy pathRouter.php
File metadata and controls
391 lines (352 loc) · 10.9 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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
<?php
/**
* The Attogram Router for PHP 7 - small, flexible, and surprisingly powerful
*
* @see https://github.com/attogram/router
* @see https://getitdaily.com/attogram-router/
*
* @license MIT
*/
declare(strict_types = 1);
namespace Attogram\Router;
use function array_pop;
use function array_shift;
use function count;
use function explode;
use function header;
use function in_array;
use function preg_match;
use function preg_replace;
use function rtrim;
use function strtr;
/**
* Class Router
* @package Attogram\Router
*/
class Router
{
const VERSION = '4.1.3';
private $control = null;
private $forceSlash = false;
private $routesExact = [];
private $routesVariable = [];
private $uri = [];
private $uriBase = '';
private $uriCount = 0;
private $uriRelative = '';
private $vars = [];
/**
* Router constructor.
*/
public function __construct()
{
// Get the Base of the URI, without 'index.php'
$this->uriBase = strtr($this->getServer('SCRIPT_NAME'), ['index.php' => '']);
// make Relative URI - remove query string from the request (everything after ?)
$this->uriRelative = preg_replace('/\?.*/', '', $this->getServer('REQUEST_URI'));
// make Relative URI - remove the Base URI
$this->uriRelative = strtr($this->uriRelative, [$this->uriBase => '/']);
// remove trailing slash from Base URI
$this->uriBase = rtrim($this->uriBase, '/');
// make array from Relative URI
$this->uri = $this->getUriArray($this->uriRelative);
// directory depth of current request
$this->uriCount = count($this->uri);
// If needed, Bypass directive auto_globals_jit
if (!isset($GLOBALS['_SERVER'])) {
/** @noinspection PhpExpressionResultUnusedInspection */
$_SERVER; // force compiler to populate _SERVER into GLOBALS
}
}
/**
* Allow a route
*
* $router->allow($route, $control);
*
* route = a string with the URI list, forward-slash delimited
*
* Exact routing:
* Home: '/'
* Page: '/foo/bar'
* - preceding and trailing slashes are optional, except for top level '/'
*
* Variable routing:
* - use a question mark to denote a URI segment as a variable
* - variables are retrieved via: $router->getVar(int $index)
* - Examples:
* '/id/?' - retrieve with getVar(0)
* '/book/?/chapter/?' - retrieve with getVar(0) and getVar(1)
* '/foo/?/?/?' - retrieve with getVar(0), getVar(1) and getVar(2)
*
* control = anything you want, a string, a closure, an array, an object, an int, a float, whatever!
*
* @param string $route
* @param mixed $control
*/
public function allow(string $route, $control)
{
// make an array of the route
$routeUri = $this->getUriArray($route);
// Is this route not the same size as the current URI?
if ($this->uriCount !== count($routeUri)) {
return; // Do not add route
}
// Single Question Mark denotes a variable routing
if (in_array('?', $routeUri)) {
$this->routesVariable[$route] = ['c' => $control, 'u' => $routeUri]; // add variable route
return; // Variable route found
}
$this->routesExact[$route] = ['c' => $control, 'u' => $routeUri]; // add exact route
}
/**
* Get the matching control for the current request
* - optionally, force a trailing slash on current request
*
* @return mixed|null
*/
public function match()
{
// if forceSlash is ON, and there is no trailing slash on current request
if ($this->forceSlash && !$this->hasTrailingSlash($this->uriRelative)) {
$this->forceSlash();
}
// Find control for current request, first with exact matching, then with variable matching
if ($this->matchExact() || $this->matchVariable()) {
return $this->control; // Match found
}
return null; // No match found
}
/**
* @return string
*/
public function getHome(): string
{
return $this->uriBase . ($this->hasTrailingSlash($this->uriBase) ? '' : '/');
}
/**
* @return string
*/
public function getHomeFull(): string
{
return$this->getHostFull() . $this->getHome();
}
/**
* @return string
*/
public function getCurrent(): string
{
return $this->uriBase . $this->uriRelative;
}
/**
* @return string
*/
public function getCurrentFull(): string
{
return $this->getHostFull() . $this->getCurrent();
}
/**
* @return string
*/
public function getHost(): string
{
$serverName = $this->getServer('SERVER_NAME');
$serverPort = $this->getServer('SERVER_PORT');
return $serverName . (!in_array((int) $serverPort, [80, 443]) ? ':' . $serverPort : '');
}
/**
* @return string
*/
public function getHostFull(): string
{
return $this->getProtocol() . '://' . $this->getHost();
}
/**
* @return string - 'http' or 'https'
*/
public function getProtocol(): string
{
$https = $this->getServer('HTTPS');
$serverPort = $this->getServer('SERVER_PORT');
return (
(!empty($https) && ($https !== 'off'))
|| ($serverPort == 443)
)
? 'https'
: 'http';
}
/**
* Get a URI variable, based on index
*
* @param int $index
* @return string|null
*/
public function getVar(int $index = 0)
{
return isset($this->vars[$index]) ? $this->vars[$index] : null;
}
/**
* Force a trailing slash on all requests? Occurs in match()
*
* @param bool $forceSlash
*/
public function setForceSlash(bool $forceSlash)
{
$this->forceSlash = $forceSlash;
}
/**
* get the value of a global _SERVER variable, or the whole _SERVER array
*
* @param string $name
* @return array|string
*/
public function getServer(string $name = '')
{
return $this->getGlobal('_SERVER', $name);
}
/**
* Redirect to a new URL, and exit
* - optionally set HTTP Response Code (301 = Moved Permanently, 302 = Found)
*
* @param string $url
* @param int $httpResponseCode
* @param bool $exitAfter - default: true
*/
public function redirect(string $url, int $httpResponseCode = 301, bool $exitAfter = true)
{
header('Location: ' . $url, true, $httpResponseCode);
if ($exitAfter) {
exit; // After a redirect, we must exit to halt any further script execution
}
}
/**
* get a value from the global _GET array, or the whole _GET array
*
* @param string $name
* @return array|string
*/
public function getGet(string $name = '')
{
return $this->getGlobal('_GET', $name);
}
/**
* get a value from the global _POST array, or the whole _POST array
*
* @param string $name
* @return array|string
*/
public function getPost(string $name = '')
{
return $this->getGlobal('_POST', $name);
}
/**
* get a value from a global array, or the whole global array
*
* @param string $global
* @param string $name
* @return array|null|string
*/
private function getGlobal(string $global, string $name = '')
{
if (!isset($GLOBALS[$global]) // Global does not exist
|| !is_array($GLOBALS[$global]) // Global is not an array
|| ($name && !isset($GLOBALS[$global][$name])) // Global variable does not exist
) {
return null;
}
if (!$name) {
return $GLOBALS[$global]; // return entire Global array
}
return $GLOBALS[$global][$name]; // return requested Global variable
}
/**
* @param string $uri
* @return bool
*/
private function hasTrailingSlash(string $uri): bool
{
return (1 === preg_match('#/$#', $uri)) ? true : false;
}
/**
* Force a trailing slash on the current request
*/
private function forceSlash()
{
// add a trailing slash to the current URL
$url = $this->getCurrentFull() . '/';
// if there is a query string in the current request
$queryString = $this->getServer('QUERY_STRING');
if (!empty($queryString)) {
// add the query string to the redirect URL
$url .= '?' . $queryString;
}
$this->redirect($url);
}
/**
* Match URI to an exact route
* @return bool
*/
private function matchExact(): bool
{
foreach ($this->routesExact as $route) {
if ($this->uri === $route['u']) { // compare the current URI array to this route URI array
$this->control = $route['c']; // set control or this exact match
return true; // exact match found
}
}
return false; // exact match not found
}
/**
* Match URI to a variable route
* @return bool
*/
private function matchVariable(): bool
{
foreach ($this->routesVariable as $route) {
$this->matchVariableVars($route['u']); // find variables
if (empty($this->vars)) {
continue; // no variable match yet
}
$this->control = $route['c']; // set control for this variable match
return true; // variable match found
}
return false; // variable match not found
}
/**
* Populate an ordered array of URI segment variables
*
* @param array $routeUri
*/
private function matchVariableVars(array $routeUri)
{
$this->vars = [];
foreach ($routeUri as $index => $route) {
if (!in_array($route, ['?', $this->uri[$index]])) {
$this->vars = [];
return; // match failed - no exact match, no variable match
}
if ($route === '?') { // found a variable
$this->vars[] = $this->uri[$index];
}
}
}
/**
* Build an array from a URI string
*
* @param string $uri
* @return array
*/
private function getUriArray(string $uri): array
{
$array = explode('/', $uri);
if ($array[0] === '') { // If first segment is empty
array_shift($array); // trim off first segment
}
if (count($array) <= 1) { // If array has 1 or less segments
return $array;
}
if ($array[count($array)-1] === '') { // If last segment is empty
array_pop($array); // trim off last segment
}
return $array;
}
}