-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.php
480 lines (392 loc) · 11.5 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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
<?php
namespace phpish\app;
if ('cli' === PHP_SAPI) return;
function env($custom_envs=[], $default='production')
{
$default_envs = [
'/^127\.0\.0\.1.*/' => 'development',
'/^localhost.*/' => 'development',
'/^.*\.dev$/' => 'development',
'/^dev\..*$/' => 'development',
];
$envs = $custom_envs + $default_envs;
foreach ($envs as $pattern=>$env_name) if (preg_match($pattern, $_SERVER['HTTP_HOST'])) return $env_name;
return $default;
}
//TODO: Deprecate in next major version
define(__NAMESPACE__.'\ENV', (
preg_match('/^127\.0\.0\.1.*/', $_SERVER['HTTP_HOST'])
or preg_match('/^localhost.*/', $_SERVER['HTTP_HOST'])
or preg_match('/^.*\.dev$/', $_SERVER['HTTP_HOST'])
or preg_match('/^dev\..*$/', $_SERVER['HTTP_HOST'])
) ? 'development' : 'production');
register_shutdown_function(function ()
{
if (!connection_aborted()) respond();
});
function any($path)
{
handler('*', $path, array(), array_slice(func_get_args(), 1));
}
function head($path)
{
handler('HEAD', $path, array(), array_slice(func_get_args(), 1));
}
function get($path)
{
handler('GET', $path, array(), array_slice(func_get_args(), 1));
}
function query($path)
{
handler('GET', $path, array('query'=>true), array_slice(func_get_args(), 1));
}
function post($path)
{
handler('POST', $path, array(), array_slice(func_get_args(), 1));
}
function post_action($path, $action)
{
handler('POST', $path, array('action'=>$action), array_slice(func_get_args(), 2));
}
function put($path)
{
handler('PUT', $path, array(), array_slice(func_get_args(), 1));
}
function delete($path)
{
handler('DELETE', $path, array(), array_slice(func_get_args(), 1));
}
function handler($method, $paths, $conds, $funcs)
{
if (!is_array($paths)) $paths = array($paths);
foreach ($paths as $key=>$val) if (!is_int($key)) _named_paths($key, $val);
foreach ($funcs as $func) _handlers(_handler_hash($method, $paths, $conds, $func));
}
function _named_paths($name=NULL, $path=NULL, $reset=false)
{
static $named_paths = array();
if ($reset) return $named_paths = array();
if (!is_null($name) and is_null($path)) return isset($named_paths[$name]) ? $named_paths[$name] : false;
$named_paths[$name] = $path;
return $named_paths;
}
function _handlers($handler=NULL, $reset=false)
{
static $handlers = array();
if ($reset) return $handlers = array();
if (is_null($handler)) return $handlers;
$handlers[] = $handler;
return $handlers;
}
function _handler_hash($method, $paths, $conds, $func)
{
return compact('method', 'paths', 'conds', 'func');
}
function next($req, $data=array())
{
$matches = array();
$handler = _next_handler_match($req, $matches);
$req['matches'] = $matches;
if (!is_null($handler))
{
if (is_callable($handler['func']))
{
return call_user_func($handler['func'], $req, $data);
}
else return response_500("Invalid handler function: {$handler['func']}");
}
return response_404('Matching handler function not found');
}
function _next_handler_match($req, &$matches)
{
static $handlers; if (!isset($handlers)) $handlers = _handlers();
while ($handler = array_shift($handlers))
{
if ($matched_handler = _handler_match($handler, $req, $matches)) return $matched_handler;
}
}
function _handler_match($handler, $req, &$matches=NULL)
{
$method_matched = (($req['method'] === $handler['method']) or ('*' === $handler['method']));
foreach ($handler['paths'] as $path)
{
if ($path_matched = _path_match($path, $req['path'], $matches)) break;
}
$action_cond_failed = (isset($handler['conds']['action'])
and (!isset($req['form']['action'])
or (strtolower(_underscorize($req['form']['action'])) !== $handler['conds']['action'])));
$query_cond_failed = (isset($handler['conds']['query']) and
(true === $handler['conds']['query']) and
empty($req['query']));
// TODO: HTTPS cond
if ($method_matched and $path_matched and !$action_cond_failed and !$query_cond_failed)
{
return $handler;
}
}
function _underscorize($str)
{
$str = preg_replace('/^[^a-zA-Z0-9]+/', '', trim($str));
return preg_replace('/[^a-zA-Z0-9]/', '_', trim($str));
}
function _path_match($path_pattern, $path, &$matches=array())
{
$regex_pattern = _path_pattern_to_regex_pattern($path_pattern);
if (1 === preg_match($regex_pattern, $path, $matches))
{
foreach ($matches as $key=>$val) { if (is_int($key)) { unset($matches[$key]); }}
return true;
}
return false;
}
//TODO: convert all \{ and \} to \x00<curllystart>, \x00<curllyend>?
function _path_pattern_to_regex_pattern($pattern)
{
$pattern = _path_pattern_optional_parts_to_regex($pattern);
$pattern = _path_pattern_named_parts_to_regex($pattern);
$pattern = strtr($pattern, array('/' => '\/'));
return "/^$pattern\$/";
}
function _path_pattern_optional_parts_to_regex($pattern)
{
$optional_parts_pattern = '/\[([^\]\[]*)\]/';
$replacement = '(\1)?';
while (true)
{
$regex_pattern = preg_replace($optional_parts_pattern, $replacement, $pattern);
if ($regex_pattern === $pattern) break;
$pattern = $regex_pattern;
}
return $pattern;
}
function _path_pattern_named_parts_to_regex($pattern)
{
$named_parts = '/{([^}]*)}/';
$pattern = preg_replace_callback
(
$named_parts,
function ($matches)
{
return _path_pattern_named_part_filters_to_regex($matches, _path_pattern_named_part_filters());
},
$pattern
);
return $pattern;
}
function _path_pattern_named_part_filters_to_regex($matches, $filters)
{
if (strpos($matches[1], ':') !== false)
{
list($subpattern_name, $pattern) = explode(':', $matches[1], 2);
$pattern = isset($filters[$pattern]) ? $filters[$pattern] : $pattern;
return "(?P<$subpattern_name>$pattern)";
}
else
{
return "(?P<{$matches[1]}>{$filters['segment']})";
}
}
function _path_pattern_named_part_filters()
{
return array
(
'word' => '\w+',
'alpha' => '[a-zA-Z]+',
'digits' => '\d+',
'number' => '\d*.?\d+',
'segment' => '[^/]+',
'any' => '.+'
);
}
function respond()
{
$response = next(request());
if (is_array($response) and (isset($response['status_code'], $response['headers'], $response['body'])))
{
exit_with($response['body'], $response['status_code'], $response['headers']);
}
exit_with($response);
}
function path_macro($paths, $func)
{
macro('*', $paths, array(), $func);
}
function macro($method, $paths, $conds, $func)
{
if (!is_array($paths)) $paths = array($paths);
$req = request();
$handler = _handler_hash($method, $paths, $conds, $func);
if (_handler_match($handler, $req, $matches))
{
if (is_callable($handler['func']))
{
$req['matches'] = $matches;
call_user_func($handler['func'], $req);
}
else trigger_error("Invalid macro handler function: {$handler['func']}", E_USER_ERROR);
}
}
function request($override=array())
{
static $request;
if (!isset($request))
{
$body = file_get_contents('php://input');
$request = array
(
'method'=> strtoupper($_SERVER['REQUEST_METHOD']),
'path'=> rawurldecode('/'.ltrim(_request_path(), '/')),
'query'=> $_GET,
'form'=> $_POST,
'server_vars'=> $_SERVER,
'headers'=> _request_headers(),
'body'=> (false === $body) ? NULL : $body
);
}
$request = $override + $request;
return $request;
}
function _request_path()
{
$path_to_executing_script = dirname($_SERVER['PHP_SELF']);
if ((1 === strlen($path_to_executing_script)) and (DIRECTORY_SEPARATOR === $path_to_executing_script))
{
$path_to_executing_script = '';
}
$path = substr($_SERVER['REQUEST_URI'], strlen($path_to_executing_script));
list($path, ) = (strpos($path, '?') !== false) ? explode('?', $path, 2) : array($path, '');
return $path;
}
function _request_headers()
{
if (function_exists('apache_request_headers')) return apache_request_headers();
$headers = array();
foreach ($_SERVER as $key=>$value)
{
if (preg_match('/^HTTP_(.*)/', $key, $matches))
{
$header = strtolower(strtr($matches[1], '_', '-'));
$headers[$header] = $value;
}
}
return $headers;
}
function _response_reason_phrase($status_code)
{
$reason_phrase = array
(
100 => 'Continue',
101 => 'Sitching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported'
);
return isset($reason_phrase[$status_code]) ? $reason_phrase[$status_code] : '';
}
function response($body, $status_code=200, $headers=array())
{
return compact('status_code', 'headers', 'body');
}
function response_301($url)
{
return response($url, 301, array('location' => $url));
}
function response_302($url)
{
return response($url, 302, array('location'=>$url));
}
function response_404($body)
{
return response($body, 404);
}
function response_500($body)
{
return response($body, 500);
}
function exit_with($body, $status_code=200, $headers=array())
{
if (!isset($headers['content-type']))
{
if (is_string($body) or is_null($body))
{
$headers['content-type'] = 'text/html';
}
else
{
$body = json_encode($body);
$headers['content-type'] = 'application/json; charset=utf-8';
}
}
flush($status_code, $headers, $body);
exit;
}
function exit_with_302($url)
{
exit_with($url, 302, array('location'=>$url));
}
function exit_with_404($body)
{
exit_with($body, 404);
}
function exit_with_500($body)
{
exit_with($body, 500);
}
function flush($status_code, $headers, $body)
{
flush_status_line($status_code);
flush_headers($headers);
flush_body($body);
}
function flush_status_line($status_code)
{
header("HTTP/1.1 $status_code "._response_reason_phrase($status_code));
}
function flush_headers($headers)
{
foreach ($headers as $field_name=>$field_value)
{
if (is_array($field_value)) foreach ($field_value as $fv) header("$field_name: $fv", false);
else header("$field_name: $field_value", false);
}
}
function flush_body($body)
{
echo $body;
}
?>