-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequest.php
More file actions
131 lines (102 loc) · 2.98 KB
/
Request.php
File metadata and controls
131 lines (102 loc) · 2.98 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
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
<?php
namespace khokonc\mvc;
use khokonc\mvc\Exceptions\HttpRedirectException;
class Request extends Validation
{
public Session $session;
public function __construct($session)
{
$this->session = $session;
}
public function ip()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
//ip from share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
//ip pass from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
public function __get($name)
{
return $this->getBody()[$name] ?? null;
}
public function isAjax()
{
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
return true;
}
return false;
}
private function getTokenWhenIsAjax()
{
return $_SERVER['X-CSRF-TOKEN'];
}
public function validate(array $rules = [])
{
$this->rules = $rules;
$keys = array_keys($rules);
foreach ($keys as $key) {
$this->attributes[$key] = $this->getBody()[$key] ?? NULL;
}
$validate = $this->exicuteValidation();
if ($validate) {
return $this->attributes;
}
if ($validate === false && $this->isAjax()) {
throw new \Exception(json_encode($this->errors), 422);
}
$this->session->setFlashMessage('errors', $this->errors);
throw new HttpRedirectException($_SERVER["HTTP_REFERER"]);
}
public function getPath()
{
$path = trim($_SERVER['REQUEST_URI'], '/');
$path = empty($path) ? '/' : $path;
$position = strpos($path, '?');
if ($position === false) {
return $path;
}
return $path = substr($path, 0, $position);
}
public function getMethod()
{
return strtolower($_SERVER['REQUEST_METHOD']);
}
public function isPost()
{
return $this->getMethod() === 'post' ? true : false;
}
public function getBody()
{
$body = [];
if ($this->getMethod() === "get") {
foreach ($_GET as $key => $value) {
$body[$key] = filter_input(INPUT_GET, $key, FILTER_SANITIZE_SPECIAL_CHARS);
}
}
if ($this->getMethod() === "post") {
foreach ($_POST as $key => $value) {
$body[$key] = filter_input(INPUT_POST, $key, FILTER_SANITIZE_SPECIAL_CHARS);
}
}
return $body;
}
public function all()
{
return json_encode($this->getBody());
}
public function verifyCsrfTocken()
{
$attributes = $this->getBody();
$token = $attributes['_token'] ?? false;
if ($token !== $this->session->getToken()) {
return false;
}
return true;
}
}