Skip to content

Commit 4e3de15

Browse files
Nyholmdbu
authored andcommitted
Added a formatter that shows the full header and body of the HTTP message (#44)
Added a formatter that shows the full header and body of the HTTP message
1 parent 15c0be7 commit 4e3de15

File tree

2 files changed

+76
-1
lines changed

2 files changed

+76
-1
lines changed

CHANGELOG.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22

33
## Unreleased
44

5+
### Added
6+
7+
- The FullHttpMessageFormatter was added
8+
59
### Fixed
610

711
- #41: Response builder broke header value
812

9-
1013
## 1.2.0 - 2016-03-29
1114

1215
### Added
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 <tobias.nyholm@gmail.com>
13+
*/
14+
class FullHttpMessageFormatter implements Formatter
15+
{
16+
/**
17+
* The maximum length of the body.
18+
*
19+
* @var int
20+
*/
21+
private $maxBodyLength;
22+
23+
/**
24+
* @param int $maxBodyLength
25+
*/
26+
public function __construct($maxBodyLength = 1000)
27+
{
28+
$this->maxBodyLength = $maxBodyLength;
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->maxBodyLength);
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->maxBodyLength);
69+
70+
return $message;
71+
}
72+
}

0 commit comments

Comments
 (0)