Skip to content

Commit 415c195

Browse files
committed
Response: added toString()
1 parent 9ca7675 commit 415c195

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

src/Http/Response.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,4 +271,30 @@ public function getBody()
271271
{
272272
return $this->body;
273273
}
274+
275+
276+
public function __toString(): string
277+
{
278+
$res = "HTTP/$this->version $this->code $this->reason\r\n";
279+
foreach ($this->headers as $name => $info) {
280+
foreach ($info[1] as $value) {
281+
$res .= $info[0] . ': ' . $value . "\r\n";
282+
}
283+
}
284+
285+
if (is_string($this->body)) {
286+
$res .= "\r\n" . $this->body;
287+
} else {
288+
ob_start(function () {});
289+
try {
290+
($this->body)();
291+
$res .= "\r\n" . ob_get_clean();
292+
} catch (\Throwable $e) {
293+
ob_end_clean();
294+
throw $e;
295+
}
296+
}
297+
298+
return $res;
299+
}
274300
}

tests/Http/Response.toString.phpt

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Http;
6+
use Tester\Assert;
7+
8+
9+
require __DIR__ . '/../bootstrap.php';
10+
11+
12+
$response = new Http\Response;
13+
$response->setProtocolVersion('3.0');
14+
$response->setCode(123, 'My Reason');
15+
$response->setHeader('X-A', 'a');
16+
$response->addHeader('X-A', 'b');
17+
$response->setBody('Hello');
18+
19+
Assert::same(
20+
"HTTP/3.0 123 My Reason\r\nX-A: a\r\nX-A: b\r\n\r\nHello",
21+
(string) $response
22+
);

0 commit comments

Comments
 (0)