Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
92.00% |
23 / 25 |
|
0.00% |
0 / 1 |
CRAP | |
0.00% |
0 / 1 |
RequestFormatter | |
92.00% |
23 / 25 |
|
0.00% |
0 / 1 |
10.05 | |
0.00% |
0 / 1 |
format | |
92.00% |
23 / 25 |
|
0.00% |
0 / 1 |
10.05 |
1 | <?php |
2 | |
3 | declare(strict_types=1); |
4 | |
5 | namespace Ndrstmr\Icap; |
6 | |
7 | use Ndrstmr\Icap\DTO\IcapRequest; |
8 | |
9 | /** |
10 | * Default implementation converting an {@link IcapRequest} into a raw string. |
11 | */ |
12 | class RequestFormatter implements RequestFormatterInterface |
13 | { |
14 | /** |
15 | * @param IcapRequest $request |
16 | */ |
17 | public function format(IcapRequest $request): string |
18 | { |
19 | $parts = parse_url($request->uri); |
20 | $host = $parts['host'] ?? ''; |
21 | |
22 | $requestLine = sprintf('%s %s ICAP/1.0', $request->method, $request->uri); |
23 | |
24 | $headers = $request->headers; |
25 | if (!isset($headers['Host'])) { |
26 | $headers['Host'] = [$host]; |
27 | } |
28 | if (!isset($headers['Encapsulated'])) { |
29 | $headers['Encapsulated'] = ['null-body=0']; |
30 | } |
31 | |
32 | $headerLines = ''; |
33 | foreach ($headers as $name => $values) { |
34 | foreach ($values as $value) { |
35 | $headerLines .= $name . ': ' . $value . "\r\n"; |
36 | } |
37 | } |
38 | |
39 | $body = ''; |
40 | if (is_resource($request->body)) { |
41 | rewind($request->body); |
42 | while (!feof($request->body)) { |
43 | $chunk = fread($request->body, 8192); |
44 | if ($chunk === false) { |
45 | break; |
46 | } |
47 | $len = dechex(strlen($chunk)); |
48 | $body .= $len . "\r\n" . $chunk . "\r\n"; |
49 | } |
50 | $body .= "0\r\n\r\n"; |
51 | } elseif (is_string($request->body) && $request->body !== '') { |
52 | $body = $request->body; |
53 | } |
54 | |
55 | return $requestLine . "\r\n" . $headerLines . "\r\n" . $body; |
56 | } |
57 | } |