Skip to content

Commit

Permalink
Merge pull request #56 from fruux/respect-contentlength
Browse files Browse the repository at this point in the history
Respecting the Content-Length header when turning HTTP bodies into strings
  • Loading branch information
evert committed Jan 5, 2016
2 parents b96385f + 769d521 commit 9374552
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 2 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
ChangeLog
=========

4.2.1 (????-??-??)
------------------

* #56: `getBodyAsString` now returns at most as many bytes as the contents of
the `Content-Length` header. This allows users to pass much larger strings
without having to copy and truncate them.


4.2.0 (2016-01-04)
------------------

Expand Down
7 changes: 6 additions & 1 deletion lib/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,12 @@ function getBodyAsString() {
if (is_null($body)) {
return '';
}
return stream_get_contents($body);
$contentLength = $this->getHeader('Content-Length');
if (null === $contentLength) {
return stream_get_contents($body);
} else {
return stream_get_contents($body, $contentLength);
}

}

Expand Down
2 changes: 1 addition & 1 deletion lib/Version.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ class Version {
/**
* Full version number
*/
const VERSION = '4.2.0';
const VERSION = '4.2.1';

}
27 changes: 27 additions & 0 deletions tests/HTTP/MessageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,33 @@ function testStringBody() {

}

/**
* It's possible that streams contains more data than the Content-Length.
*
* The request object should make sure to never emit more than
* Content-Length, if Content-Length is set.
*
* This is in particular useful when respoding to range requests with
* streams that represent files on the filesystem, as it's possible to just
* seek the stream to a certain point, set the content-length and let the
* request object do the rest.
*/
function testLongStreamToStringBody() {

$body = fopen('php://memory', 'r+');
fwrite($body, 'abcdefg');
fseek($body, 2);

$message = new MessageMock();
$message->setBody($body);
$message->setHeader('Content-Length', '4');

$this->assertEquals(
'cdef',
$message->getBodyAsString()
);

}

function testGetEmptyBodyStream() {

Expand Down

0 comments on commit 9374552

Please sign in to comment.