Skip to content

Commit

Permalink
Reduced complexity of ResponseSenderMiddleware
Browse files Browse the repository at this point in the history
  • Loading branch information
dutekvejin committed Jun 25, 2017
1 parent 82d35b0 commit d8071af
Showing 1 changed file with 24 additions and 17 deletions.
41 changes: 24 additions & 17 deletions src/ResponseSenderMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,43 +16,50 @@
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;

/**
* @author Dusan Vejin <[email protected]>
*/
class ResponseSenderMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, DelegateInterface $delegate): ResponseInterface
public function process(ServerRequestInterface $request, DelegateInterface $delegate) : ResponseInterface
{
$response = $delegate->process($request);

if (!headers_sent()) {
$http = sprintf(
'HTTP/%s %s %s',
$response->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase()
);
$this->sendHeaders($response);
$this->sendOutput($response->getBody());

header($http, true, $response->getStatusCode());
return $response;
}

foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), false);
}
}
protected function sendHeaders(ResponseInterface $response)
{
if (headers_sent()) {
return;
}

$stream = $response->getBody();
$protocolVersion = $response->getProtocolVersion();
$statusCode = $response->getStatusCode();
$reasonPhrase = $response->getReasonPhrase();

header("HTTP/$protocolVersion $statusCode $reasonPhrase", true, $statusCode);

foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header("$name: $value", false);
}
}
}

protected function sendOutput(StreamInterface $stream)
{
if ($stream->isSeekable()) {
$stream->rewind();
}

while (false === $stream->eof()) {
echo $stream->read(1024 * 8);
}

return $response;
}
}

0 comments on commit d8071af

Please sign in to comment.