forked from estadao-digital/test-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRouter.php
More file actions
63 lines (49 loc) · 1.6 KB
/
Router.php
File metadata and controls
63 lines (49 loc) · 1.6 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
<?php
class Router
{
private $request;
private $metodosHttpSuportados = array(
"GET",
"POST"
);
function __construct(IRequest $request) {
$this->request = $request;
}
function __call($nome, $args) {
list($rota, $metodo) = $args;
if(!in_array(strtoupper($nome), $this->metodosHttpSuportados)){
$this->trataMetodoInvalido();
}
$this->{strtolower($nome)}[$this->formataRota($rota)] = $metodo;
}
//remove / no final da rota
private function formataRota($rota) {
$resposta = rtrim($rota, '/');
if ($resposta === ''){
return '/';
}
return $resposta;
}
private function trataMetodoInvalido() {
header("{$this->request->serverProtocol} 405 Method Not Allowed");
}
private function trataRequestPadrao() {
header("{$this->request->serverProtocol} 404 Not Found");
}
//resolve a rota
function resolve() {
$tradutorDeMetodo = $this->{strtolower($this->request->requestMethod)};
$rotaFormatada = $this->formataRota($this->request->requestUri);
$metodo = $tradutorDeMetodo[$rotaFormatada];
if(is_null($metodo))
{
$this->trataRequestPadrao();
return;
}
echo call_user_func_array($metodo, array($this->request));
}
function __destruct() {
$this->resolve();
}
}
?>