Skip to content
This repository has been archived by the owner on Jan 29, 2020. It is now read-only.

Commit

Permalink
Merge pull request #200 from markstory/issue-199
Browse files Browse the repository at this point in the history
Fix incompatibilities between Unseekable streams and SapiStreamEmitter
  • Loading branch information
weierophinney committed Sep 7, 2016
2 parents 26a846f + 92b1e34 commit 8e4c176
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/Response/SapiStreamEmitter.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,14 @@ public function emit(ResponseInterface $response, $maxBufferLength = 8192)
private function emitBody(ResponseInterface $response, $maxBufferLength)
{
$body = $response->getBody();
$body->rewind();
if ($body->isSeekable()) {
$body->rewind();

while (! $body->eof()) {
echo $body->read($maxBufferLength);
while (! $body->eof()) {
echo $body->read($maxBufferLength);
}
} else {
echo $body;
}
}

Expand All @@ -76,6 +80,13 @@ private function emitBodyRange(array $range, ResponseInterface $response, $maxBu

++$last; //zero-based position
$body = $response->getBody();

if (!$body->isSeekable()) {
$contents = $body->getContents();
echo substr($contents, $first, $last - $first);
return;
}

$body->seek($first);
$pos = $first;

Expand Down
28 changes: 28 additions & 0 deletions test/Response/SapiStreamEmitterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use PHPUnit_Framework_TestCase as TestCase;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use Zend\Diactoros\CallbackStream;
use Zend\Diactoros\Response;
use Zend\Diactoros\Response\SapiStreamEmitter;
use ZendTest\Diactoros\TestAsset\HeaderStack;
Expand All @@ -24,6 +25,19 @@ public function setUp()
$this->emitter = new SapiStreamEmitter();
}

public function testEmitCallbackStreamResponse()
{
$stream = new CallbackStream(function () {
return 'it works';
});
$response = (new Response())
->withStatus(200)
->withBody($stream);
ob_start();
$this->emitter->emit($response);
$this->assertEquals('it works', ob_get_clean());
}

public function testDoesNotInjectContentLengthHeaderIfStreamSizeIsUnknown()
{
$stream = $this->prophesize('Psr\Http\Message\StreamInterface');
Expand Down Expand Up @@ -66,4 +80,18 @@ public function testContentRange($header, $body, $expected)
$this->emitter->emit($response);
$this->assertEquals($expected, ob_get_clean());
}

public function testContentRangeUnseekableBody()
{
$body = new CallbackStream(function () {
return 'Hello world';
});
$response = (new Response())
->withBody($body)
->withHeader('Content-Range', 'bytes 3-6/*');

ob_start();
$this->emitter->emit($response);
$this->assertEquals('lo w', ob_get_clean());
}
}

0 comments on commit 8e4c176

Please sign in to comment.