-
Notifications
You must be signed in to change notification settings - Fork 2
/
App.php
317 lines (261 loc) 路 8.65 KB
/
App.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
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
<?php
/*
* Inphinit
*
* Copyright (c) 2024 Guilherme Nascimento (brcontainer@yahoo.com.br)
*
* Released under the MIT license
*/
namespace Inphinit;
use Inphinit\Http\Response;
use Inphinit\Viewing\View;
class App
{
private static $configs;
private $routes = array();
private $paramRoutes = array();
private $namespacePrefix = '';
private $pathPrefix = '/';
private $hasParams = false;
private $paramPatterns = array(
'alnum' => '[\da-zA-Z]+',
'alpha' => '[a-zA-Z]+',
'decimal' => '\d+\.\d+',
'num' => '\d+',
'nospace' => '[^/\s]+',
'uuid' => '[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}',
'version' => '\d+\.\d+(\.\d+(-[\da-zA-Z]+(\.[\da-zA-Z]+)*(\+[\da-zA-Z]+(\.[\da-zA-Z]+)*)?)?)?'
);
private $patternNames;
private $beforeRE = array('\\:', '\\<', '\\>', '\\*');
private $afterRE = array(':', '<', '>', '.*?');
public function __construct()
{
$this->patternNames = implode('|', array_keys($this->paramPatterns));
}
/**
* Get application configs
*
* @param string $key
* @return mixed
*/
public static function config($key, $value = null)
{
if (self::$configs === null) {
self::$configs = inphinit_sandbox('configs/app.php');
}
if (array_key_exists($key, self::$configs)) {
if ($value == null) {
return self::$configs[$key];
}
self::$configs[$key] = $value;
}
}
/**
* Register a callback or script for a route
*
* @param string|array $methods
* @param string $path
* @param string|callable $callback
* @return void
*/
public function action($methods, $path, $callback)
{
$path = $this->pathPrefix . ltrim($path, '/');
if (strpos($path, '<') !== false) {
$routes = &$this->paramRoutes;
$this->hasParams = true;
} else {
$routes = &$this->routes;
}
if (isset($routes[$path]) === false) {
$routes[$path] = array();
}
if (is_array($methods)) {
foreach ($methods as $method) {
$routes[$path][strtoupper($method)] = $callback;
}
} else {
$routes[$path][strtoupper($methods)] = $callback;
}
}
/**
* Prefix controller on scope
*
* @param string $prefix Set controller prefix
*/
public function setNamespace($prefix)
{
$this->namespacePrefix = $ns;
}
/**
* Prefix route paths on scope
*
* @param string $prefix Set path prefix
*/
public function setPath($prefix)
{
$this->pathPrefix = $prefix;
}
/**
* Register a callback for a URI pattern
*
* @param string $pattern URI pattern
* @param \Closure $callback Callback
*/
public function scope($pattern, \Closure $callback)
{
$patterns = &$this->paramPatterns;
$regex = '#[<]([A-Za-z]\w+)(\:(' . $this->patternNames . '))?[>]#';
$pattern = str_replace($this->beforeRE, $this->afterRE, preg_quote($pattern));
$pattern = preg_replace_callback($regex, function ($matches) use (&$patterns) {
return '(?P<' . $matches[1] . '>' . (
isset($matches[3]) ? $patterns[$matches[3]] : '[^/]+'
) . ')';
}, $pattern);
if (preg_match('#^' . $pattern . '#', INPHINIT_URL, $params)) {
$path = parse_url($params[0], PHP_URL_PATH);
if ($path) {
$this->pathPrefix = $path;
}
foreach ($params as $index => $value) {
if (is_int($index)) {
unset($params[$index]);
}
}
$callback($this, $params);
$this->namespacePrefix = '';
$this->pathPrefix = '/';
}
}
/**
* Execute application
*
* @return bool Returns false if request matches a file in built-in web server, otherwise returns true
*/
public function exec()
{
$code = self::$configs['maintenance'] ? 503 : http_response_code();
$callback = null;
$params = null;
$output = null;
if ($code === 200) {
if (PHP_SAPI === 'cli-server' && $this->fileInBuiltIn()) {
return false;
}
$path = INPHINIT_PATH;
$method = $_SERVER['REQUEST_METHOD'];
if (isset($this->routes[$path])) {
$routes = &$this->routes[$path];
if (isset($routes[$method])) {
$callback = $routes[$method];
} elseif (isset($routes['ANY'])) {
$callback = $routes['ANY'];
} else {
$code = 405;
}
} elseif ($this->hasParams) {
$this->params($method, $code, $callback, $params);
} else {
$code = 404;
}
}
if ($code === 200) {
if (is_string($callback) && strpos($callback, '::') !== false) {
$parsed = explode('::', $callback, 2);
$callback = '\\Controller\\' . $this->namespacePrefix . $parsed[0];
$callback = array(new $callback, $parsed[1]);
}
$output = $callback($params);
} else {
http_response_code($code);
$code = array('status' => $code);
inphinit_sandbox('errors.php', $code);
}
self::forward($output);
return true;
}
/**
* Create or remove a pattern for URL slugs
*
* @param string $pattern Set pattern for URL slug params like this /foo/<var:pattern>
* @return void
*/
public function setPattern($pattern, $regex)
{
$this->paramPatterns[preg_quote($pattern)] = $regex;
$this->patternNames = implode('|', array_keys($this->paramPatterns));
}
/**
* Get routes from current scope and parents
*
* @return array
*/
public function routes()
{
return $this->routes + $this->paramRoutes;
}
public static function forward(&$output = null)
{
if (class_exists('\\Inphinit\\Viewing\\View', false)) {
View::dispatch();
}
echo $output;
if (class_exists('\\Inphinit\\Event', false)) {
Event::trigger('done');
}
}
private function params($method, &$code, &$callback, &$params)
{
$code = 404;
$patterns = &$this->paramPatterns;
$getParams = '#\\\\[<]([A-Za-z]\\w+)(\\\\:(' . $this->patternNames . ')|)\\\\[>]#';
$limit = 20;
$total = count($this->paramRoutes);
for ($indexRoutes = 0; $indexRoutes < $total; $indexRoutes += $limit) {
$slice = array_slice($this->paramRoutes, $indexRoutes, $limit);
$j = 0;
$callbacks = array();
foreach ($slice as $regexPath => &$param) {
$callbacks[] = $param;
$param = '#route_' . (++$j) . '>' . preg_quote($regexPath);
}
$groupRegex = implode(')|(', $slice);
$groupRegex = preg_replace($getParams, '(?<$1><$3>)', $groupRegex);
$groupRegex = str_replace('<>)', '[^/]+)', $groupRegex);
foreach ($patterns as $pattern => $regex) {
$groupRegex = str_replace('<' . $pattern . '>)', $regex . ')', $groupRegex);
}
$groupRegex = str_replace('#route_', '?<route_', $groupRegex);
if (preg_match('#^((?J)(' . $groupRegex . '))$#', INPHINIT_PATH, $params)) {
foreach ($params as $index => $value) {
if ($value === '' || is_int($index)) {
unset($params[$index]);
} else if (strpos($index, 'route_') === 0) {
$callbacks = $callbacks[substr($index, 6) - 1];
unset($params[$index]);
}
}
$code = 200;
if (isset($callbacks[$method])) {
$callback = $callbacks[$method];
} elseif (isset($callbacks['ANY'])) {
$callback = $callbacks['ANY'];
} else {
$code = 405;
}
break;
}
}
}
private function fileInBuiltIn()
{
$path = INPHINIT_PATH;
return (
$path !== '/' &&
strpos($path, '.') !== 0 &&
strpos($path, '/.') === false &&
is_file(INPHINIT_ROOT . '/public' . $path)
);
}
}