Completed
Push — develop ( 2e1df2...27dbda )
by Mathieu
03:22
created

Request::setRequestUri()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Suricate;
3
4
class Request
5
{
6
    const HTTP_METHOD_GET       = 'GET';
7
    const HTTP_METHOD_POST      = 'POST';
8
    const HTTP_METHOD_PUT       = 'PUT';
9
    const HTTP_METHOD_DELETE    = 'DELETE';
10
    const HTTP_METHOD_HEAD      = 'HEAD';
11
    const HTTP_METHOD_OPTIONS   = 'OPTIONS';
12
13
    private $method = self::HTTP_METHOD_GET;
14
    private $methods = array(
15
            self::HTTP_METHOD_GET       => 'GET',
16
            self::HTTP_METHOD_POST      => 'POST',
17
            self::HTTP_METHOD_PUT       => 'PUT',
18
            self::HTTP_METHOD_DELETE    => 'DELETE',
19
            self::HTTP_METHOD_HEAD      => 'HEAD',
20
            self::HTTP_METHOD_OPTIONS   => 'OPTIONS'
21
        );
22
23
    private $httpCodeString = [
24
        100 => 'Continue',
25
        101 => 'Switching Protocols',
26
        102 => 'Processing',
27
        200 => 'OK',
28
        201 => 'Created',
29
        202 => 'Accepted',
30
        203 => 'Non-Authoritative Information',
31
        204 => 'No Content',
32
        205 => 'Reset Content',
33
        206 => 'Partial Content',
34
        207 => 'Multi-Status',
35
        208 => 'Already Reported',
36
        226 => 'IM Used',
37
        250 => 'Low on Storage Space',
38
        300 => 'Multiple Choices',
39
        301 => 'Moved Permanently',
40
        302 => 'Found',
41
        303 => 'See Other',
42
        304 => 'Not Modified',
43
        305 => 'Use Proxy',
44
        306 => '306 Switch Proxy',
45
        307 => 'Temporary Redirect',
46
        308 => 'Permanent Redirect',
47
        400 => 'Bad Request',
48
        401 => 'Unauthorized',
49
        402 => 'Payment Required',
50
        403 => 'Forbidden',
51
        404 => 'Not Found',
52
        405 => 'Method Not Allowed',
53
        406 => 'Not Acceptable',
54
        407 => 'Proxy Authentication Required',
55
        408 => 'Request Timeout',
56
        409 => 'Conflict',
57
        410 => 'Gone',
58
        411 => 'Length Required',
59
        412 => 'Precondition Failed',
60
        413 => 'Request Entity Too Large',
61
        414 => 'Request-URI Too Long',
62
        415 => 'Unsupported Media Type',
63
        416 => 'Requested Range Not Satisfiable',
64
        417 => 'Expectation Failed',
65
        422 => 'Unprocessable Entity',
66
        423 => 'Locked',
67
        424 => 'Failed Dependency',
68
        425 => 'Unordered Collection',
69
        426 => 'Upgrade Required',
70
        428 => 'Precondition Required',
71
        429 => 'Too Many Requests',
72
        431 => 'Request Header Fields Too Large',
73
        444 => 'No Response',
74
        449 => 'Retry With',
75
        450 => 'Blocked by Windows Parental Controls',
76
        494 => 'Request Header Too Large',
77
        495 => 'Cert Error',
78
        496 => 'No Cert',
79
        497 => 'HTTP to HTTPS',
80
        499 => 'Client Closed Request',
81
        500 => 'Internal Server Error',
82
        501 => 'Not Implemented',
83
        502 => 'Bad Gateway',
84
        503 => 'Service Unavailable',
85
        504 => 'Gateway Timeout',
86
        505 => 'HTTP Version Not Supported',
87
        506 => 'Variant Also Negotiates',
88
        507 => 'Insufficient Storage',
89
        508 => 'Loop Detected',
90
        509 => 'Bandwidth Limit Exceeded',
91
        510 => 'Not Extended',
92
        511 => 'Network Authentication Required'
93
    ];
94
95
    private $httpCode;
96
    private $headers;
97
    private $requestUri;
98
    private $url;
99
    private $body;
100
    private $path;
101
    private $query;
102
103 9
    public function __construct()
104
    {
105 9
        $this->headers  = array();
106 9
        $this->httpCode = 200;
107 9
    }
108
109 1
    public function parse()
110
    {
111 1
        if (isset($_SERVER['REQUEST_URI'])) {
112 1
            $this->setRequestUri($_SERVER['REQUEST_URI']);
113 1
            $parseResult = parse_url($_SERVER['REQUEST_URI']);
114 1
            $this->path     = dataGet($parseResult, 'path');
115 1
            $this->query    = dataGet($parseResult, 'query');
116
        }
117
118 1
        if (isset($_SERVER['REQUEST_METHOD'])) {
119 1
            $this->setMethod($_SERVER['REQUEST_METHOD']);
120
        }
121 1
        if (isset($_POST['_method'])) {
122 1
            $this->setMethod($_POST['_method']);
123
        }
124 1
    }
125
126 2
    public function setMethod($method)
127
    {
128 2
        if (!isset($this->methods[$method])) {
129 1
            throw new \InvalidArgumentException('Invalid HTTP Method ' . $method);
130
        }
131
132 2
        $this->method = $method;
133
134 2
        return $this;
135
    }
136
137 2
    public function getMethod()
138
    {
139 2
        return $this->method;
140
    }
141
142 1
    public function setUrl($url)
143
    {
144 1
        $this->url = $url;
145
146 1
        return $this;
147
    }
148 1
    public function getUrl()
149
    {
150 1
        return $this->url;
151
    }
152
153 2
    public function setRequestUri($uri)
154
    {
155 2
        $this->requestUri = $uri;
156
157 2
        return $this;
158
    }
159
160 3
    public function getRequestUri()
161
    {
162 3
        return $this->requestUri;
163
    }
164
165 1
    public function getPath()
166
    {
167 1
        return $this->path;
168
    }
169
170 1
    public function getQuery()
171
    {
172 1
        return $this->query;
173
    }
174
175 1
    public static function getPostParam($variable, $defaultValue = null)
176
    {
177 1
        if (isset($_POST[$variable])) {
178 1
            return $_POST[$variable];
179
        }
180 1
        return $defaultValue;
181
    }
182
183 1
    public static function getParam($variable, $defaultValue = null)
184
    {
185 1
        if (isset($_GET[$variable])) {
186 1
            return $_GET[$variable];
187
        }
188 1
        if (isset($_POST[$variable])) {
189 1
            return $_POST[$variable];
190
        }
191
        
192 1
        return $defaultValue;
193
    }
194
195 1
    public static function hasParam($variable)
196
    {
197 1
        return isset($_GET[$variable]) || isset($_POST[$variable]);
198
    }
199
200
       
201 1
    public function setHeaders($headers)
202
    {
203 1
        $this->headers = $headers;
204
205 1
        return $this;
206
    }
207
208 1
    public function addHeader($header, $value)
209
    {
210 1
        $this->headers[$header] = $value;
211
212 1
        return $this;
213
    }
214
215 1
    public function getHeaders()
216
    {
217 1
        return $this->headers;
218
    }
219
220
221 1
    public function setContentType(string $contentType, $encoding = null): Request
222
    {
223 1
        if ($encoding !== null) {
224 1
            $contentType .= '; charset=' . $encoding;
225
        }
226 1
        $this->addHeader('Content-type', $contentType);
227
228 1
        return $this;
229
    }
230
231 1
    public function setBody(string $body): Request
232
    {
233 1
        $this->body = $body;
234
235 1
        return $this;
236
    }
237
238 1
    public function getBody(): string
239
    {
240 1
        return $this->body;
241
    }
242
243
244
    public function write()
245
    {
246
        if (!headers_sent()) {
247
            if (substr(php_sapi_name(), 0, 3) == 'cgi') {
248
                $headerString = 'Status: ' . self::getStringForHttpCode();
0 ignored issues
show
Bug Best Practice introduced by
The method Suricate\Request::getStringForHttpCode() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

248
                $headerString = 'Status: ' . self::/** @scrutinizer ignore-call */ getStringForHttpCode();
Loading history...
249
            } else {
250
                $headerString = 'HTTP/1.1 ' . self::getStringForHttpCode();
251
            }
252
253
            header($headerString);
254
255
            // Send headers
256
            foreach ($this->headers as $headerName => $headerValue) {
257
                header($headerName . ':' . $headerValue);
258
            }
259
        }
260
261
        /**
262
         TODO HANDLE HTTP RESPONSE CODE
263
         */
264
        if ($this->httpCode !== null) {
265
266
        }
267
268
        // Send body
269
        echo $this->body;
270
    }
271
272
    //
273
    // HTTP Code
274
    //
275
276 1
    public function setHttpCode($code): Request
277
    {
278 1
        $this->httpCode = $code;
279
280 1
        return $this;
281
    }
282
283 1
    public function getHttpCode()
284
    {
285 1
        return $this->httpCode;
286
    }
287
288
    public function flash($type, $data)
289
    {
290
        Flash::write($type, $data);
291
        
292
        return $this;
293
    }
294
295
    public function flashData($name, $value)
296
    {
297
        Flash::write('data', array($name => $value));
298
299
        return $this;
300
    }
301
302
    public function redirect($url, $httpCode = 302)
303
    {
304
        $this->setHttpCode($httpCode);
305
        $this->addHeader('Location', $url);
306
307
        $this->write();
308
        die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
309
    }
310
311
    public function redirectWithSuccess($url, $message)
312
    {
313
        $this
314
            ->flash('success', $message)
315
            ->redirect($url);
316
    }
317
318
    public function redirectWithInfo($url, $message)
319
    {
320
        $this
321
            ->flash('info', $message)
322
            ->redirect($url);
323
    }
324
325
    public function redirectWithError($url, $message)
326
    {
327
        $this
328
            ->flash('error', $message)
329
            ->redirect($url);
330
    }
331
332
    public function redirectWithData($url, $key, $value)
333
    {
334
        $this
335
            ->flashData($key, $value)
336
            ->redirect($url);
337
    }
338
339
    /**
340
     * Check if request has a 200 OK Code
341
     *
342
     * @return boolean
343
     */
344 1
    public function isOK(): bool
345
    {
346 1
        return ( $this->httpCode == 200 );
347
    }
348
349
    /**
350
     * Check if request has a 3XX HTTP code
351
     *
352
     * @return boolean
353
     */
354 1
    public function isRedirect(): bool
355
    {
356 1
        return ( $this->httpCode >= 300 && $this->httpCode < 400 );
357
    }
358
359
    /**
360
     * Check is request has a 4XX HTTP code
361
     *
362
     * @return boolean
363
     */
364 1
    public function isClientError(): bool
365
    {
366 1
        return ( $this->httpCode >= 400 && $this->httpCode < 500 );
367
    }
368
369
    /**
370
     * Check if request has a 5XX HTTP code
371
     *
372
     * @return boolean
373
     */
374 1
    public function isServerError(): bool
375
    {
376 1
        return ( $this->httpCode >= 500 && $this->httpCode < 600 );
377
    }
378
379 1
    private function getStringForHttpCode()
380
    {
381 1
        if (isset($this->httpCodeString[$this->httpCode])) {
382 1
            return $this->httpCode . ' ' . $this->httpCodeString[$this->httpCode];
383
        }
384 1
    }
385
}
386