Add request class. Not really tested yet.
[rock.divinelegy.git] / Services / Http / HttpResponse.php
1 <?php
2
3 namespace Services\Http;
4
5 use Services\Http\IHttpResponse;
6 use Exception;
7
8 class HttpResponse implements IHttpResponse
9 {
10 private $_statusCode = 200;
11 private $_headers = array();
12 private $_body;
13 private $_isRedirect = false;
14
15 public function setStatusCode($code)
16 {
17 if(!is_int($code) || (100 > $code) || (599 < $code)) {
18 throw new Exception(sprintf('Invalid HTTP response code, %u', $code));
19 }
20
21 $this->_isRedirect = (300 <= $code) && (307 >= $code);
22 $this->_statusCode = $code;
23
24 return $this;
25 }
26
27 public function isRedirect()
28 {
29 return $this->_isRedirect;
30 }
31
32 public function setHeader($name, $value)
33 {
34 $value = (string) $value;
35
36 $this->_headers[$name] = $value;
37
38 return $this;
39 }
40
41 public function getHeaders()
42 {
43 return $this->_headers;
44 }
45
46 private function sendHeaders()
47 {
48 $statusCodeSent = false;
49
50 if(!count($this->_headers)) {
51 return $this;
52 }
53
54 foreach($this->_headers as $headerName => $headerValue) {
55 if(!$statusCodeSent) {
56 header(
57 sprintf('%s:%s', $headerName, $headerValue),
58 false,
59 $this->_statusCode);
60
61 $statusCodeSent = true;
62 }
63 }
64
65 return $this;
66 }
67
68 public function setBody($content)
69 {
70 $this->_body = $content;
71
72 return $this;
73 }
74
75 public function getBody()
76 {
77 return $this->_body;
78 }
79
80
81 private function sendBody()
82 {
83 echo $this->_body;
84
85 return $this;
86 }
87
88 public function sendResponse()
89 {
90 $this->sendHeaders()
91 ->sendBody();
92 }
93 }