-
Notifications
You must be signed in to change notification settings - Fork 3
/
Controller.php
59 lines (46 loc) · 1.25 KB
/
Controller.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
<?php namespace TooBasic;
class Controller
{
public static function dispatch(string $path = null)
{
if (!isset($path))
$path = $_SERVER['REQUEST_URI'];
if (false !== strpos($path, '?'))
$path = strstr($path, '?', true);
$params = explode('/', substr($path, 1));
$params = array_map('rawurldecode', $params);
$action = array_shift($params);
if ('' === $action)
$action = 'index';
new static(strtolower($_SERVER['REQUEST_METHOD']), $action, $params);
}
final private function __construct(string $method, string $action, array $params)
{
if ('head' == $method)
$method = 'get';
try
{
$this->_construct($method, $action, $params);
if (method_exists($this, $method . ucfirst($action)))
return $this->{$method . ucfirst($action)}(...$params);
$this->$method(...array_merge(array($action), $params));
}
catch (\Exception $e)
{
$this->_handle($e);
}
}
protected function _construct(string $method, string $action, array $params)
{
}
public function __call(string $method, array $arguments)
{
throw new Exception('404 - Unknown method: '. $method);
}
protected function _handle(\Exception $e)
{
if (!headers_sent())
http_response_code($e instanceof Exception ? $e->getCode() : 500);
print $e;
}
}