3 * Zend Framework (http://framework.zend.com/)
5 * @see http://github.com/zendframework/zend-diactoros for the canonical source repository
6 * @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
10 namespace Zend\Diactoros\Response;
12 use Psr\Http\Message\ResponseInterface;
14 use Zend\Diactoros\RelativeStream;
16 class SapiStreamEmitter implements EmitterInterface
21 * Emits a response for a PHP SAPI environment.
23 * Emits the status line and headers via the header() function, and the
24 * body content via the output buffer.
26 * @param ResponseInterface $response
27 * @param int $maxBufferLength Maximum output buffering size for each iteration
29 public function emit(ResponseInterface $response, $maxBufferLength = 8192)
32 throw new RuntimeException('Unable to emit response; headers already sent');
35 $response = $this->injectContentLength($response);
37 $this->emitStatusLine($response);
38 $this->emitHeaders($response);
41 $range = $this->parseContentRange($response->getHeaderLine('Content-Range'));
43 if (is_array($range) && $range[0] === 'bytes') {
44 $this->emitBodyRange($range, $response, $maxBufferLength);
48 $this->emitBody($response, $maxBufferLength);
52 * Emit the message body.
54 * @param ResponseInterface $response
55 * @param int $maxBufferLength
57 private function emitBody(ResponseInterface $response, $maxBufferLength)
59 $body = $response->getBody();
61 if ($body->isSeekable()) {
65 if (! $body->isReadable()) {
70 while (! $body->eof()) {
71 echo $body->read($maxBufferLength);
76 * Emit a range of the message body.
79 * @param ResponseInterface $response
80 * @param int $maxBufferLength
82 private function emitBodyRange(array $range, ResponseInterface $response, $maxBufferLength)
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 >= $maxBufferLength && ! $body->eof()) {
104 $contents = $body->read($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 * @param string $header
120 * @return false|array [unit, first, last, length]; returns false if no
121 * content range or an invalid content range is provided
123 private function parseContentRange($header)
125 if (preg_match('/(?P<unit>[\w]+)\s+(?P<first>\d+)-(?P<last>\d+)\/(?P<length>\d+|\*)/', $header, $matches)) {
128 (int) $matches['first'],
129 (int) $matches['last'],
130 $matches['length'] === '*' ? '*' : (int) $matches['length'],