better download handling #8
[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 } else {
63 header(
64 sprintf('%s: %s', $headerName, $headerValue));
65 }
66 }
67
68 return $this;
69 }
70
71 public function setBody($content)
72 {
73 $this->_body = $content;
74
75 return $this;
76 }
77
78 public function getBody()
79 {
80 return $this->_body;
81 }
82
83
84 private function sendBody()
85 {
86 echo $this->_body;
87
88 return $this;
89 }
90
91 public function sendResponse()
92 {
93 $this->sendHeaders()
94 ->sendBody();
95 }
96
97 public function download($path)
98 {
99 $this->sendResponse();
100 $fd = fopen($path, 'r');
101 if(!$fd) throw new Exception ('Failed to open file.');
102
103 while(!feof($fd)) {
104 $buffer = fread($fd, 2048);
105 print $buffer;
106 }
107 fclose ($fd);
108
109 exit();
110 }
111 }