4 * @see https://github.com/laminas/laminas-httphandlerrunner for the canonical source repository
5 * @copyright https://github.com/laminas/laminas-httphandlerrunner/blob/master/COPYRIGHT.md
6 * @license https://github.com/laminas/laminas-httphandlerrunner/blob/master/LICENSE.md New BSD License
9 declare(strict_types=1);
11 namespace Laminas\HttpHandlerRunner\Emitter;
13 use Psr\Http\Message\ResponseInterface;
15 use function preg_match;
19 class SapiStreamEmitter implements EmitterInterface
24 * @var int Maximum output buffering size for each iteration.
26 private $maxBufferLength;
28 public function __construct(int $maxBufferLength = 8192)
30 $this->maxBufferLength = $maxBufferLength;
34 * Emits a response for a PHP SAPI environment.
36 * Emits the status line and headers via the header() function, and the
37 * body content via the output buffer.
39 public function emit(ResponseInterface $response) : bool
41 $this->assertNoPreviousOutput();
42 $this->emitHeaders($response);
43 $this->emitStatusLine($response);
47 $range = $this->parseContentRange($response->getHeaderLine('Content-Range'));
49 if (null === $range || 'bytes' !== $range[0]) {
50 $this->emitBody($response);
54 $this->emitBodyRange($range, $response);
59 * Emit the message body.
61 private function emitBody(ResponseInterface $response) : void
63 $body = $response->getBody();
65 if ($body->isSeekable()) {
69 if (! $body->isReadable()) {
74 while (! $body->eof()) {
75 echo $body->read($this->maxBufferLength);
80 * Emit a range of the message body.
82 private function emitBodyRange(array $range, ResponseInterface $response) : void
84 list($unit, $first, $last, $length) = $range;
86 $body = $response->getBody();
88 $length = $last - $first + 1;
90 if ($body->isSeekable()) {
96 if (! $body->isReadable()) {
97 echo substr($body->getContents(), $first, $length);
101 $remaining = $length;
103 while ($remaining >= $this->maxBufferLength && ! $body->eof()) {
104 $contents = $body->read($this->maxBufferLength);
105 $remaining -= strlen($contents);
110 if ($remaining > 0 && ! $body->eof()) {
111 echo $body->read($remaining);
116 * Parse content-range header
117 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16
119 * @return null|array [unit, first, last, length]; returns null if no
120 * content range or an invalid content range is provided
122 private function parseContentRange(string $header) : ?array
124 if (! preg_match('/(?P<unit>[\w]+)\s+(?P<first>\d+)-(?P<last>\d+)\/(?P<length>\d+|\*)/', $header, $matches)) {
130 (int) $matches['first'],
131 (int) $matches['last'],
132 $matches['length'] === '*' ? '*' : (int) $matches['length'],