Skip to content

Commit 226ba9f

Browse files
authored
Merge pull request #128 from ostrolucky/handle-binary-in-full-http-formatter
Omit binary body in FullHttpMessageFormatter
2 parents f7fa350 + 8baa5e1 commit 226ba9f

File tree

3 files changed

+34
-7
lines changed

3 files changed

+34
-7
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
99

1010
## Unreleased
1111

12+
- Omitted binary body in FullHttpMessageFormatter. `[binary stream omitted]` will be shown instead.
13+
1214
### Added
1315

1416
- New Header authentication method for arbitrary header authentication.

spec/Formatter/FullHttpMessageFormatterSpec.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,4 +227,25 @@ function it_does_not_format_no_seekable_response(ResponseInterface $response, St
227227
STR;
228228
$this->formatResponse($response)->shouldReturn($expectedMessage);
229229
}
230+
231+
function it_omits_body_with_null_bytes(RequestInterface $request, StreamInterface $stream)
232+
{
233+
$this->beConstructedWith(1);
234+
235+
$stream->isSeekable()->willReturn(true);
236+
$stream->rewind()->shouldBeCalled();
237+
$stream->__toString()->willReturn("\0");
238+
$request->getBody()->willReturn($stream);
239+
$request->getMethod()->willReturn('GET');
240+
$request->getRequestTarget()->willReturn('/foo');
241+
$request->getProtocolVersion()->willReturn('1.1');
242+
$request->getHeaders()->willReturn([]);
243+
244+
$expectedMessage = <<<STR
245+
GET /foo HTTP/1.1
246+
247+
[binary stream omitted]
248+
STR;
249+
$this->formatRequest($request)->shouldReturn($expectedMessage);
250+
}
230251
}

src/Formatter/FullHttpMessageFormatter.php

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -76,20 +76,24 @@ public function formatResponse(ResponseInterface $response)
7676
*/
7777
private function addBody(MessageInterface $request, $message)
7878
{
79+
$message .= "\n";
7980
$stream = $request->getBody();
8081
if (!$stream->isSeekable() || 0 === $this->maxBodyLength) {
8182
// Do not read the stream
82-
return $message."\n";
83+
return $message;
8384
}
8485

85-
if (null === $this->maxBodyLength) {
86-
$message .= "\n".$stream->__toString();
87-
} else {
88-
$message .= "\n".mb_substr($stream->__toString(), 0, $this->maxBodyLength);
86+
$data = $stream->__toString();
87+
$stream->rewind();
88+
89+
if (preg_match('/[\x00-\x1F\x7F]/', $data)) {
90+
return $message.'[binary stream omitted]';
8991
}
9092

91-
$stream->rewind();
93+
if (null === $this->maxBodyLength) {
94+
return $message.$data;
95+
}
9296

93-
return $message;
97+
return $message.mb_substr($data, 0, $this->maxBodyLength);
9498
}
9599
}

0 commit comments

Comments
 (0)