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

Commit

Permalink
Return the original response if the body size has changed.
Browse files Browse the repository at this point in the history
- Per @ezimuel, when the original response body has been written to,
  `FinalHandler` was still returning the 404 response. This patch
  ensures that if the body size changes, the response will still be
  returned.
  • Loading branch information
weierophinney committed Jun 25, 2015
1 parent ab9ca14 commit 69057f1
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/FinalHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@
*/
class FinalHandler
{
/**
* Original response body size.
*
* @var int
*/
private $bodySize = 0;

/**
* @var array
*/
Expand All @@ -39,6 +46,10 @@ public function __construct(array $options = [], ResponseInterface $response = n
{
$this->options = $options;
$this->response = $response;

if ($response) {
$this->bodySize = $response->getBody()->getSize();
}
}

/**
Expand Down Expand Up @@ -73,6 +84,16 @@ public function __invoke(RequestInterface $request, ResponseInterface $response,
return $response;
}

// If the response passed is the same as the one at instantiation,
// check to see if the body size has changed; if it has, return
// the response, as the message body has been written to.
if ($this->response
&& $this->response === $response
&& $this->bodySize !== $response->getBody()->getSize()
) {
return $response;
}

return $this->create404($request, $response);
}

Expand Down
18 changes: 18 additions & 0 deletions test/FinalHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ public function test404ResponseIncludesOriginalRequestUri()
$this->assertContains($originalUrl, (string) $response->getBody());
}

/**
* @group 12
*/
public function testReturnsResponseIfItDoesNotMatchResponsePassedToConstructor()
{
$psrResponse = new PsrResponse();
Expand All @@ -132,4 +135,19 @@ public function testReturnsResponseIfItDoesNotMatchResponsePassedToConstructor()
$result = $final(new Request(new PsrRequest()), $passedResponse);
$this->assertSame($passedResponse, $result);
}

/**
* @group 12
*/
public function testReturnsResponseIfBodyLengthHasChanged()
{
$psrResponse = new PsrResponse();
$response = new Response($psrResponse);
$final = new FinalHandler([], $response);

$response->write('return this response');

$result = $final(new Request(new PsrRequest()), $response);
$this->assertSame($response, $result);
}
}

0 comments on commit 69057f1

Please sign in to comment.