Passed
Push — master ( 0ee5cf...8209bc )
by Fran
02:47
created

Request::getServer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
namespace PSFS\base;
3
4
use PSFS\base\types\traits\Helper\ServerTrait;
5
use PSFS\base\types\traits\SingletonTrait;
6
7
/**
8
 * Class Request
9
 * @package PSFS
10
 */
11
class Request
12
{
13
    use SingletonTrait;
14
    use ServerTrait;
15
16
    const VERB_GET = 'GET';
17
    const VERB_POST = 'POST';
18
    const VERB_PUT = 'PUT';
19
    const VERB_DELETE = 'DELETE';
20
    const VERB_OPTIONS = 'OPTIONS';
21
    const VERB_HEAD = 'HEAD';
22
    const VERB_PATCH = 'PATCH';
23
24
    /**
25
     * @var array
26
     */
27
    protected $cookies;
28
    /**
29
     * @var array
30
     */
31
    protected $upload;
32
    /**
33
     * @var array
34
     */
35
    protected $header;
36
    /**
37
     * @var array
38
     */
39
    protected $data;
40
    /**
41
     * @var array
42
     */
43
    protected $raw = [];
44
    /**
45
     * @var array
46
     */
47
    protected $query;
48
    /**
49
     * @var bool
50
     */
51
    private $isLoaded = false;
52
53 2
    public function init()
54
    {
55 2
        $this->setServer(is_array($_SERVER) ? $_SERVER : []);
56 2
        $this->cookies = is_array($_COOKIE) ? $_COOKIE : [];
57 2
        $this->upload = is_array($_FILES) ? $_FILES : [];
58 2
        $this->header = $this->parseHeaders();
59 2
        $this->data = is_array($_REQUEST) ? $_REQUEST : [];
60 2
        $this->query = is_array($_GET) ? $_GET : [];
61 2
        $this->raw = json_decode(file_get_contents('php://input'), true) ?: [];
62 2
        $this->isLoaded = true;
63 2
    }
64
65
    /**
66
     * Método que devuelve las cabeceras de la petición
67
     * @return array
68
     */
69 2
    private function parseHeaders()
70
    {
71 2
        return getallheaders();
72
    }
73
74
    /**
75
     * Método que verifica si existe una cabecera concreta
76
     * @param $header
77
     *
78
     * @return boolean
79
     */
80 11
    public function hasHeader($header)
81
    {
82 11
        return array_key_exists($header, $this->header);
83
    }
84
85
86
    /**
87
     * Método que indica si una petición tiene cookies
88
     * @return boolean
89
     */
90 1
    public function hasCookies()
91
    {
92 1
        return (null !== $this->cookies && 0 !== count($this->cookies));
93
    }
94
95
    /**
96
     * Método que indica si una petición tiene cookies
97
     * @return boolean
98
     */
99 1
    public function hasUpload()
100
    {
101 1
        return (null !== $this->upload && 0 !== count($this->upload));
102
    }
103
104
    /**
105
     * Método que devuelve el TimeStamp de la petición
106
     *
107
     * @param boolean $formatted
108
     *
109
     * @return string
110
     */
111
    public static function getTimestamp($formatted = false)
112
    {
113
        return self::getInstance()->getTs($formatted);
114
    }
115
116
    /**
117
     * Método que devuelve una cabecera de la petición si existe
118
     * @param string $name
119
     * @param string $default
120
     *
121
     * @return string|null
122
     */
123 10
    public static function header($name, $default = null)
124
    {
125 10
        return self::getInstance()->getHeader($name,  $default);
126
    }
127
128
    /**
129
     * @param string $name
130
     * @param string $default
131
     * @return string|null
132
     */
133 10
    public function getHeader($name, $default = null)
134
    {
135 10
        $header = null;
136 10
        if ($this->hasHeader($name)) {
137
            $header = $this->header[$name];
138 10
        } else if(array_key_exists('h_' . strtolower($name), $this->query)) {
139
            $header = $this->query['h_' . strtolower($name)];
140 10
        } else if(array_key_exists('HTTP_' . strtoupper(str_replace('-', '_', $name)), $this->server)) {
141
            $header = $this->getServer('HTTP_' . strtoupper(str_replace('-', '_', $name)));
142
        }
143 10
        return $header ?: $default;
144
    }
145
146
    /**
147
     * Método que devuelve la url solicitada
148
     * @return string|null
149
     */
150 1
    public static function requestUri()
151
    {
152 1
        return self::getInstance()->getRequestUri();
153
    }
154
155
    /**
156
     * Método que determina si se ha solicitado un fichero
157
     * @return boolean
158
     */
159 5
    public function isFile()
160
    {
161 5
        return preg_match('/\.[a-z0-9]{2,4}$/', $this->getRequestUri()) !== 0;
162
    }
163
164
    /**
165
     * Get query params
166
     *
167
     * @param string $queryParams
168
     *
169
     * @return mixed
170
     */
171
    public function getQuery($queryParams)
172
    {
173
        return array_key_exists($queryParams, $this->query) ? $this->query[$queryParams] : null;
174
    }
175
176
    /**
177
     * Get all query params
178
     *
179
     * @return mixed
180
     */
181 3
    public function getQueryParams()
182
    {
183 3
        return $this->query;
184
    }
185
186
    /**
187
     * Método que devuelve un parámetro de la solicitud
188
     * @param string $param
189
     *
190
     * @return string|null
191
     */
192
    public function get($param)
193
    {
194
        return array_key_exists($param, $this->data) ? $this->data[$param] : null;
195
    }
196
197
    /**
198
     * Método que devuelve todos los datos del Request
199
     * @return array
200
     */
201 4
    public function getData()
202
    {
203 4
        return array_merge($this->data, $this->raw);
204
    }
205
206
    /**
207
     * @return array
208
     */
209
    public function getRawData() {
210
        return $this->raw;
211
    }
212
213
    /**
214
     * Método que devuelve el valor de una cookie en caso de que exista
215
     * @param string $name
216
     *
217
     * @return string
218
     */
219 1
    public function getCookie($name)
220
    {
221 1
        return array_key_exists($name, $this->cookies) ? $this->cookies[$name] : null;
222
    }
223
224
    /**
225
     * Método que devuelve los files subidos por POST
226
     * @param $name
227
     *
228
     * @return array
229
     */
230
    public function getFile($name)
231
    {
232
        return array_key_exists($name, $this->upload) ? $this->upload[$name] : array();
233
    }
234
235
    /**
236
     * Método que realiza una redirección a la url dada
237
     * @param string $url
238
     */
239
    public function redirect($url = null)
240
    {
241
        if (null === $url) {
242
            $url = $this->getServer('HTTP_ORIGIN');
243
        }
244
        ob_start();
245
        header('Location: ' . $url);
246
        ob_end_clean();
247
        Security::getInstance()->updateSession();
248
        exit(t('Redirect...'));
249
    }
250
251
    /**
252
     * Devuelve la url completa de base
253
     * @param boolean $hasProtocol
254
     * @return string
255
     */
256 2
    public function getRootUrl($hasProtocol = true)
257
    {
258 2
        $url = $this->getServerName();
259 2
        $protocol = $hasProtocol ? $this->getProtocol() : '';
260 2
        if (!empty($protocol)) {
261 2
            $url = $protocol . $url;
262
        }
263 2
        $url = $this->checkServerPort($url);
264 2
        return $url;
265
    }
266
267
    /**
268
     * @param string $url
269
     * @return string
270
     */
271 2
    protected function checkServerPort(string $url): string
272
    {
273 2
        $port = (integer)$this->getServer('SERVER_PORT');
274 2
        $host = $this->getServer('HTTP_HOST');
275 2
        if(!empty($host)) {
276
            $parts = explode(':', $host);
277
            $hostPort = (integer)end($parts);
278
            if(count($parts) > 1 && $hostPort !== $port) {
279
                $port = $hostPort;
280
            }
281
        }
282 2
        if (!in_array($port, [80, 443], true)) {
283 2
            $url .= ':' . $port;
284
        }
285 2
        return $url;
286
    }
287
288
}
289