|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace HnrAzevedo\Router; |
|
4
|
|
|
|
|
5
|
|
|
use HnrAzevedo\Validator\Validator; |
|
6
|
|
|
|
|
7
|
|
|
trait Helper{ |
|
8
|
|
|
use CheckTrait, ControllerTrait; |
|
9
|
|
|
|
|
10
|
|
|
protected function getProtocol(): string |
|
11
|
|
|
{ |
|
12
|
|
|
if((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')){ |
|
13
|
|
|
return 'ajax'; |
|
14
|
|
|
} |
|
15
|
|
|
|
|
16
|
|
|
/* ONLY FOR DEBUG CONDITION */ |
|
17
|
|
|
if(!array_key_exists('REQUEST_METHOD',$_SERVER)){ |
|
18
|
|
|
return 'get'; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
return strtolower($_SERVER['REQUEST_METHOD']); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
protected function getData(): ?array |
|
25
|
|
|
{ |
|
26
|
|
|
return [ |
|
27
|
|
|
'POST' => $_POST, |
|
28
|
|
|
'GET' => $_GET, |
|
29
|
|
|
'FILES' => $_FILES |
|
30
|
|
|
]; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
protected function import(string $path) |
|
34
|
|
|
{ |
|
35
|
|
|
foreach (scandir($path) as $routeFile) { |
|
36
|
|
|
if(pathinfo($path.DIRECTORY_SEPARATOR.$routeFile, PATHINFO_EXTENSION) === 'php'){ |
|
37
|
|
|
require_once($path. DIRECTORY_SEPARATOR .$routeFile); |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
protected function ControllerForm($controller, string $method, array $values){ |
|
43
|
|
|
if(Validator::execute($values)){ |
|
44
|
|
|
|
|
45
|
|
|
$this->check_role(); |
|
46
|
|
|
|
|
47
|
|
|
$role = ($method !== 'method') ? $method : $this->getData()['POST']['role']; |
|
48
|
|
|
$data = (!is_null($values)) ? json_decode($values['data']) : null; |
|
|
|
|
|
|
49
|
|
|
$controller->$role($data); |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
protected function Controller(string $controll): void |
|
54
|
|
|
{ |
|
55
|
|
|
$data = $this->getData(); |
|
56
|
|
|
|
|
57
|
|
|
foreach ($data['GET'] as $name => $value) { |
|
58
|
|
|
$controll = str_replace('{'.$name.'}',$value,$controll); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
$this->check_controllsettable($controll); |
|
62
|
|
|
|
|
63
|
|
|
$this->check_controllexist($controll); |
|
64
|
|
|
|
|
65
|
|
|
$this->check_controllmethod($controll); |
|
66
|
|
|
|
|
67
|
|
|
$controller = 'Controllers\\' . ucfirst(explode(':',$controll)[0]); |
|
68
|
|
|
$controller = new $controller(); |
|
69
|
|
|
$method = explode(':',$controll)[1]; |
|
70
|
|
|
|
|
71
|
|
|
if( ( $this->getProtocol() == 'form') ){ |
|
72
|
|
|
$this->ControllerForm($controller, $method, $data['POST']); |
|
73
|
|
|
}else { |
|
74
|
|
|
$controller->$method($data); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
protected function explodeRoute(bool $bar, array $url): array |
|
79
|
|
|
{ |
|
80
|
|
|
return explode( '/', $bar ? substr($url, 0, -1) : $url ); |
|
|
|
|
|
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
} |