1 <?php
2
3 namespace Docolight\Http;
4
5 use Exception;
6 use Docolight\Http\Contracts\Arrayable;
7
8 9 10 11 12
13 abstract class MimeResponse extends Response
14 {
15 16 17 18 19
20 protected $stringRepresentation;
21
22 23 24
25 public function getBody()
26 {
27 return (empty($this->body)) ? $this->getEmpty() : $this->body;
28 }
29
30 31 32
33 public function finalize()
34 {
35 list($status, $headers, $body) = parent::finalize();
36
37 $this->stringRepresentation = $this->convertToStringRepresentation($body);
38 $this->length = strlen($this->stringRepresentation);
39
40 $this->headers->set('Content-Type', $this->getContentType());
41 $this->headers->set('Content-Length', $this->length);
42
43 return array($status, $headers, $body);
44 }
45
46 47 48
49 public function write($body, $replace = false)
50 {
51 if ($body) {
52 return $this->innerWrite($body, $replace);
53 }
54 }
55
56 57 58 59 60 61 62 63
64 protected function innerWrite(Arrayable $body, $replace = false)
65 {
66 if ($replace === true) {
67 $this->body = $body;
68 } elseif ($replace === false) {
69 $this->body->fill($body->castToArray());
70 }
71
72 return $this;
73 }
74
75 76 77
78 protected function sendBody($body)
79 {
80 if (trim(strtoupper(def($_SERVER, 'REQUEST_METHOD', ''))) !== 'HEAD') {
81 echo $this->stringRepresentation;
82 }
83 }
84
85 86 87 88 89 90 91
92 abstract protected function convertToStringRepresentation(Arrayable $body);
93
94
95 96 97 98 99
100 abstract protected function getContentType();
101 }
102