Skip to content

Commit db33418

Browse files
committed
make most methods fluid + add new 'json()' method
1 parent 098e3be commit db33418

File tree

1 file changed

+51
-7
lines changed

1 file changed

+51
-7
lines changed

src/Http/Response.php

Lines changed: 51 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
namespace Corviz\Http;
44

5+
use Exception;
6+
use JsonSerializable;
7+
58
class Response
69
{
710
/*
@@ -83,22 +86,51 @@ class Response
8386
*
8487
* @param string $key
8588
* @param string $value
89+
*
90+
* @return $this;
8691
*/
87-
public function addHeader($key, $value)
92+
public function addHeader($key, $value): Response
8893
{
8994
$this->headers[$key] = $value;
95+
96+
return $this;
97+
}
98+
99+
/**
100+
* Builds a json response
101+
*
102+
* @param $data
103+
*
104+
* @return $this
105+
*/
106+
public function json($data): Response
107+
{
108+
$json = json_encode($data);
109+
110+
if ($json === false) {
111+
throw new Exception("Could not convert data to json!");
112+
}
113+
114+
$this->addHeader('Content-Type', 'application/json');
115+
$this->setBody($json);
116+
117+
return $this;
90118
}
91119

92120
/**
93121
* Remove a header.
94122
*
95123
* @param string $key
124+
*
125+
* @return $this
96126
*/
97-
public function removeHeader(string $key)
127+
public function removeHeader(string $key): Response
98128
{
99129
if (isset($this->headers[$key])) {
100130
unset($this->headers[$key]);
101131
}
132+
133+
return $this;
102134
}
103135

104136
/**
@@ -125,12 +157,12 @@ protected function sendBody()
125157
* Sends header to the client through 'header'
126158
* php function.
127159
*
128-
* @throws \Exception
160+
* @throws Exception
129161
*/
130162
protected function sendHeaders()
131163
{
132164
if (headers_sent()) {
133-
throw new \Exception('Headers already sent');
165+
throw new Exception('Headers already sent');
134166
}
135167

136168
foreach ($this->headers as $name => $value) {
@@ -140,27 +172,39 @@ protected function sendHeaders()
140172

141173
/**
142174
* @param string|null $body
175+
*
176+
* @return $this
143177
*/
144-
public function setBody(string $body = null)
178+
public function setBody(string $body = null): Response
145179
{
146180
$this->body = $body;
181+
182+
return $this;
147183
}
148184

149185
/**
150186
* Set response http code.
151187
*
152188
* @param int $code
189+
*
190+
* @return $this
153191
*/
154-
public function setCode(int $code)
192+
public function setCode(int $code): Response
155193
{
156194
$this->code = $code;
195+
196+
return $this;
157197
}
158198

159199
/**
160200
* @param string $contents
201+
*
202+
* @return $this
161203
*/
162-
public function write(string $contents)
204+
public function write(string $contents): Response
163205
{
164206
$this->body .= $contents;
207+
208+
return $this;
165209
}
166210
}

0 commit comments

Comments
 (0)