Skip to content

Commit b834017

Browse files
committed
Added a formatter that shows the full header and body of the HTTP message
1 parent 15c0be7 commit b834017

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
<?php
2+
3+
namespace Http\Message\Formatter;
4+
5+
use Http\Message\Formatter;
6+
use Psr\Http\Message\RequestInterface;
7+
use Psr\Http\Message\ResponseInterface;
8+
9+
/**
10+
* A formatter that prints the complete HTTP message.
11+
*
12+
* @author Tobias Nyholm <[email protected]>
13+
*/
14+
class FullHttpMessageFormatter implements Formatter
15+
{
16+
/**
17+
* The maximum length of the body.
18+
*
19+
* @var int
20+
*/
21+
private $maxBodyLendth;
22+
23+
/**
24+
* @param int $maxBodyLendth number of chars.
25+
*/
26+
public function __construct($maxBodyLendth = 1000)
27+
{
28+
$this->maxBodyLendth = $maxBodyLendth;
29+
}
30+
31+
/**
32+
* {@inheritdoc}
33+
*/
34+
public function formatRequest(RequestInterface $request)
35+
{
36+
$message = sprintf(
37+
"%s %s HTTP/%s\n",
38+
$request->getMethod(),
39+
$request->getRequestTarget(),
40+
$request->getProtocolVersion()
41+
);
42+
43+
foreach ($request->getHeaders() as $name => $values) {
44+
$message .= $name.': '.implode(', ', $values)."\n";
45+
}
46+
47+
$message .= "\n".mb_substr($request->getBody()->__toString(), 0, $this->maxBodyLendth);
48+
49+
return $message;
50+
}
51+
52+
/**
53+
* {@inheritdoc}
54+
*/
55+
public function formatResponse(ResponseInterface $response)
56+
{
57+
$message = sprintf(
58+
"HTTP/%s %s %s\n",
59+
$response->getProtocolVersion(),
60+
$response->getStatusCode(),
61+
$response->getReasonPhrase()
62+
);
63+
64+
foreach ($response->getHeaders() as $name => $values) {
65+
$message .= $name.': '.implode(', ', $values)."\n";
66+
}
67+
68+
$message .= "\n".mb_substr($response->getBody()->__toString(), 0, $this->maxBodyLendth);
69+
70+
return $message;
71+
}
72+
}

0 commit comments

Comments
 (0)