-
Notifications
You must be signed in to change notification settings - Fork 2
/
Router.php
62 lines (62 loc) · 1.38 KB
/
Router.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
<?php
class Router
{
private $request;
private $supportedHttpMethods = array(
"GET",
"POST"
);
function __construct(IRequest $request)
{
$this->request = $request;
}
function __call($name, $args)
{
list($route, $method) = $args;
if(!in_array(strtoupper($name), $this->supportedHttpMethods))
{
$this->invalidMethodHandler();
}
$this->{strtolower($name)}[$this->formatRoute($route)] = $method;
}
/**
* Removes trailing forward slashes from the right of the route.
* @param route (string)
*/
private function formatRoute($route)
{
$result = rtrim($route, '/');
if ($result === '')
{
return '/';
}
return $result;
}
private function invalidMethodHandler()
{
header("{$this->request->serverProtocol} 405 Method Not Allowed");
}
private function defaultRequestHandler()
{
header("{$this->request->serverProtocol} 404 Not Found");
}
/**
* Resolves a route
*/
function resolve()
{
$methodDictionary = $this->{strtolower($this->request->requestMethod)};
$formatedRoute = $this->formatRoute($this->request->requestUri);
$method = $methodDictionary[$formatedRoute];
if(is_null($method))
{
$this->defaultRequestHandler();
return;
}
echo call_user_func_array($method, array($this->request));
}
function __destruct()
{
$this->resolve();
}
}