|
1
|
|
|
<?php |
|
2
|
|
|
namespace Fastpress\Http; |
|
3
|
|
|
|
|
4
|
|
|
class Response{ |
|
5
|
|
|
private $code = 200; |
|
6
|
|
|
private $text = "OK"; |
|
7
|
|
|
private $headers = []; |
|
8
|
|
|
private $protocol = "HTTP/1.1"; |
|
9
|
|
|
private $body; |
|
10
|
|
|
|
|
11
|
|
|
public function setResponse($code = 200, $text = "OK"){ |
|
12
|
|
|
$this->code = $code; |
|
13
|
|
|
$this->text = $text; |
|
14
|
|
|
} |
|
15
|
|
|
|
|
16
|
|
|
public function setBody($body){ |
|
17
|
|
|
$this->body = $body; |
|
18
|
|
|
return $this; |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
public function addHeader($name, $value){ |
|
22
|
|
|
$this->headers[$name] = (string) $value; |
|
23
|
|
|
return $this; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function setCode($code){ |
|
27
|
|
|
if($code < 100 || $code > 599){ |
|
28
|
|
|
throw new \LogicException(sprintf( |
|
29
|
|
|
"%s is unsuported HTTP status code ", $code |
|
30
|
|
|
)); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
$this->code = $code; |
|
34
|
|
|
return $this; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function getCode(){ |
|
38
|
|
|
return $this->code; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
public function getText(){ |
|
42
|
|
|
return $this->text; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function getHeaders(){ |
|
46
|
|
|
return $this->headers; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
public function render(){ |
|
50
|
|
|
if(!headers_sent()){ |
|
51
|
|
|
header($this->fullHeaderStatus()); |
|
52
|
|
|
$this->renderHeaders(); |
|
53
|
|
|
return $this->body; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
protected function renderHeaders(){ |
|
59
|
|
|
foreach ($this->headers as $key => $headerValue) { |
|
60
|
|
|
header($key . ": " . $headerValue); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
public function redirect($url, $code = 301){ |
|
65
|
|
|
$this->addHeader("Location", $url); |
|
66
|
|
|
$this->setCode($code); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
public function disableBrowserCache() { |
|
70
|
|
|
$this->headers[] = "Cache-Control: no-cache, no-store, must-revalidate"; |
|
71
|
|
|
$this->headers[] = "Pragma: no-cache"; |
|
72
|
|
|
$this->headers[] = "Expires: Thu, 26 Feb 1970 20:00:00 GMT"; |
|
73
|
|
|
return $this; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
private function fullHeaderStatus(){ |
|
77
|
|
|
return $this->protocol ." ". $this->code ." ". $this->text; |
|
78
|
|
|
} |
|
79
|
|
|
} |