1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Class Response |
4
|
|
|
* |
5
|
|
|
* @package Faulancer\Http |
6
|
|
|
* @author Florian Knapp <[email protected]> |
7
|
|
|
*/ |
8
|
|
|
namespace Faulancer\Http; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class Response |
12
|
|
|
*/ |
13
|
|
|
class Response extends AbstractHttp |
14
|
|
|
{ |
15
|
|
|
|
16
|
|
|
const HTTP_STATUS_CODES = [ |
17
|
|
|
200 => 'Ok', |
18
|
|
|
301 => 'Moved Permanently', |
19
|
|
|
304 => 'Not Modified', |
20
|
|
|
400 => 'Bad Request', |
21
|
|
|
401 => 'Unauthorized', |
22
|
|
|
403 => 'Forbidden', |
23
|
|
|
404 => 'Not Found', |
24
|
|
|
405 => 'Method Not Allowed', |
25
|
|
|
408 => 'Request Timeout', |
26
|
|
|
410 => 'Gone', |
27
|
|
|
418 => 'I\'m a teapot', |
28
|
|
|
429 => 'Too Many Requests', |
29
|
|
|
500 => 'Internal Server Error', |
30
|
|
|
501 => 'Not Implemented', |
31
|
|
|
502 => 'Bad Gateway', |
32
|
|
|
503 => 'Service Unavailable', |
33
|
|
|
504 => 'Gateway Timed-out', |
34
|
|
|
505 => 'HTTP Version Not Supported', |
35
|
|
|
507 => 'Insufficient Storage', |
36
|
|
|
]; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* The status code (default: 200) |
40
|
|
|
* @var integer |
41
|
|
|
*/ |
42
|
|
|
protected $code = 200; |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* The response body |
46
|
|
|
* @var string |
47
|
|
|
*/ |
48
|
|
|
protected $content; |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Set response code |
52
|
|
|
* |
53
|
|
|
* @param integer $code |
54
|
|
|
*/ |
55
|
|
|
public function setCode(int $code = 200) |
56
|
|
|
{ |
57
|
|
|
$this->code = $code; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Get response code |
62
|
|
|
* |
63
|
|
|
* @return int |
64
|
|
|
*/ |
65
|
|
|
public function getCode() :int |
66
|
|
|
{ |
67
|
|
|
return $this->code; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Set response body |
72
|
|
|
* |
73
|
|
|
* @param mixed $content |
74
|
|
|
*/ |
75
|
|
|
public function setContent($content) |
76
|
|
|
{ |
77
|
|
|
$this->content = $content; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* Get response body and set headers |
82
|
|
|
* |
83
|
|
|
* @return mixed |
84
|
|
|
*/ |
85
|
|
|
public function getContent() |
86
|
|
|
{ |
87
|
|
|
$this->setResponseHeader(); |
88
|
|
|
return $this->content; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
/** |
92
|
|
|
* @codeCoverageIgnore Is covered because usage of php built-in function |
93
|
|
|
*/ |
94
|
|
|
public function setResponseHeader() |
95
|
|
|
{ |
96
|
|
|
$protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/2.0'; |
97
|
|
|
header($protocol . ' ' . $this->getCode() . ' ' . self::HTTP_STATUS_CODES[$this->getCode()]); |
98
|
|
|
} |
99
|
|
|
|
100
|
|
|
/** |
101
|
|
|
* If object is getting outputted |
102
|
|
|
* |
103
|
|
|
* @return string |
104
|
|
|
*/ |
105
|
|
|
public function __toString() |
106
|
|
|
{ |
107
|
|
|
return (string)$this->getContent(); |
108
|
|
|
} |
109
|
|
|
|
110
|
|
|
} |