Skip to content

Commit 7b66c9c

Browse files
committed
Response: added toString()
1 parent 7a0a78d commit 7b66c9c

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

src/Http/Response.php

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

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+
$response->toString()
22+
);

0 commit comments

Comments
 (0)