Skip to content

Commit 5162ebd

Browse files
committed
ResponseFactory: added fromString()
1 parent 7b66c9c commit 5162ebd

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/Http/ResponseFactory.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,27 @@ public function fromGlobals(): Response
3333

3434
return $response;
3535
}
36+
37+
38+
public function fromString(string $message): Response
39+
{
40+
$response = new Response;
41+
$parts = explode("\r\n\r\n", $message, 2);
42+
$response->setBody($parts[1] ?? '');
43+
44+
$headers = explode("\r\n", $parts[0]);
45+
$status = array_shift($headers);
46+
47+
if (!preg_match('#^HTTP/([\d.]+) (\d+) (.+)$#', $status, $m)) {
48+
throw new Nette\InvalidArgumentException("Invalid status line '$status'.");
49+
}
50+
$response->setProtocolVersion($m[1]);
51+
$response->setCode((int) $m[2], $m[3]);
52+
53+
foreach ($headers as $header) {
54+
$parts = explode(': ', $header, 2);
55+
$response->addHeader($parts[0], $parts[1]);
56+
}
57+
return $response;
58+
}
3659
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+
$serializer = new Http\ResponseFactory;
13+
$response = $serializer->fromString("HTTP/3.0 123 My Reason\r\nX-A: a\r\nX-A: b\r\n\r\nHello");
14+
15+
Assert::same(123, $response->getCode());
16+
Assert::same('3.0', $response->getProtocolVersion());
17+
Assert::same('My Reason', $response->getReasonPhrase());
18+
19+
Assert::same(['X-A' => ['a', 'b']], $response->getHeaders());
20+
21+
Assert::same('Hello', $response->getBody());

0 commit comments

Comments
 (0)