diff --git a/CHANGELOG.md b/CHANGELOG.md index 508fc72..18ca302 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) ------------------ diff --git a/lib/Message.php b/lib/Message.php index 3fedee5..5c6887d 100644 --- a/lib/Message.php +++ b/lib/Message.php @@ -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); + } } diff --git a/lib/Version.php b/lib/Version.php index 693cefe..789ee45 100644 --- a/lib/Version.php +++ b/lib/Version.php @@ -14,6 +14,6 @@ class Version { /** * Full version number */ - const VERSION = '4.2.0'; + const VERSION = '4.2.1'; } diff --git a/tests/HTTP/MessageTest.php b/tests/HTTP/MessageTest.php index 15703a6..0ca19ba 100644 --- a/tests/HTTP/MessageTest.php +++ b/tests/HTTP/MessageTest.php @@ -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() {