Skip to content

Commit

Permalink
Hotfix: now Streaming Response is optional
Browse files Browse the repository at this point in the history
  • Loading branch information
roxblnfk committed Mar 22, 2022
1 parent a0cc561 commit 3be8bac
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions src/PSR7Worker.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@
*/
class PSR7Worker implements PSR7WorkerInterface
{
public int $chunk_size = 8 * 1024;
/**
* @var int Preferred chunk size for streaming output.
* if not greater than 0, then streaming response is turned off
*/
public int $chunkSize = 0;

/**
* @var HttpWorker
Expand Down Expand Up @@ -113,11 +117,18 @@ public function waitRequest(): ?ServerRequestInterface
*/
public function respond(ResponseInterface $response): void
{
$this->httpWorker->respondStream(
$response->getStatusCode(),
$this->streamToGenerator($response->getBody()),
$response->getHeaders()
);
if ($this->chunkSize > 0) {
$this->httpWorker->respondStream(
$response->getStatusCode(),
$this->streamToGenerator($response->getBody()),
$response->getHeaders()
);
} else {
$this->httpWorker->respond(
$response->getStatusCode(),
(string)$response->getBody(),
$response->getHeaders());
}
}

/**
Expand All @@ -128,17 +139,17 @@ private function streamToGenerator(StreamInterface $stream): Generator
{
$stream->rewind();
$size = $stream->getSize();
if ($size !== null && $size < $this->chunk_size) {
if ($size !== null && $size < $this->chunkSize) {
return (string)$stream;
}
$sum = 0;
while (!$stream->eof()) {
if ($size === null) {
$chunk = $stream->read($this->chunk_size);
$chunk = $stream->read($this->chunkSize);
} else {
$left = $size - $sum;
$chunk = $stream->read(\min($this->chunk_size, $left));
if ($left <= $this->chunk_size && \strlen($chunk) === $left) {
$chunk = $stream->read(\min($this->chunkSize, $left));
if ($left <= $this->chunkSize && \strlen($chunk) === $left) {
return $chunk;
}
}
Expand Down

0 comments on commit 3be8bac

Please sign in to comment.