Skip to content

Commit 43e2829

Browse files
committed
ResponseFactory: added fromString() & fromUrl()
1 parent 02808c8 commit 43e2829

File tree

3 files changed

+79
-0
lines changed

3 files changed

+79
-0
lines changed

src/Http/ResponseFactory.php

+39
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,45 @@ public function fromGlobals(): Response
3232
}
3333

3434

35+
public function fromString(string $message): Response
36+
{
37+
$response = new Response;
38+
$parts = explode("\r\n\r\n", $message, 2);
39+
$headers = explode("\r\n", $parts[0]);
40+
$this->parseStatus($response, array_shift($headers));
41+
$this->parseHeaders($response, $headers);
42+
$response->setBody($parts[1] ?? '');
43+
return $response;
44+
}
45+
46+
47+
public function fromUrl(string $url): Response
48+
{
49+
$response = new Response;
50+
$response->setBody(file_get_contents($url));
51+
$headers = [];
52+
foreach ($http_response_header as $header) {
53+
if (substr($header, 0, 5) === 'HTTP/') {
54+
$headers = [];
55+
}
56+
$headers[] = $header;
57+
}
58+
$this->parseStatus($response, array_shift($headers));
59+
$this->parseHeaders($response, $headers);
60+
return $response;
61+
}
62+
63+
64+
private function parseStatus(Response $response, string $status): void
65+
{
66+
if (!preg_match('#^HTTP/([\d.]+) (\d+) (.+)$#', $status, $m)) {
67+
throw new Nette\InvalidArgumentException("Invalid status line '$status'.");
68+
}
69+
$response->setProtocolVersion($m[1]);
70+
$response->setCode((int) $m[2], $m[3]);
71+
}
72+
73+
3574
private function parseHeaders(Response $response, array $headers): void
3675
{
3776
foreach ($headers as $header) {
+21
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+
$factory = new Http\ResponseFactory;
13+
$response = $factory->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());
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
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+
$factory = new Http\ResponseFactory;
13+
$response = $factory->fromUrl('http://nette.org');
14+
15+
Assert::same(200, $response->getCode());
16+
Assert::same('1.1', $response->getProtocolVersion());
17+
Assert::same('OK', $response->getReasonPhrase());
18+
Assert::same(['SAMEORIGIN'], $response->getHeaders()['X-Frame-Options']);
19+
Assert::contains('Nette Foundation', $response->getBody());

0 commit comments

Comments
 (0)