3 * @see https://github.com/zendframework/zend-diactoros for the canonical source repository
4 * @copyright Copyright (c) 2015-2017 Zend Technologies USA Inc. (http://www.zend.com)
5 * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
8 namespace Zend\Diactoros\Response;
10 use Psr\Http\Message\ResponseInterface;
12 use Zend\Diactoros\RelativeStream;
14 class SapiStreamEmitter implements EmitterInterface
19 * Emits a response for a PHP SAPI environment.
21 * Emits the status line and headers via the header() function, and the
22 * body content via the output buffer.
24 * @param ResponseInterface $response
25 * @param int $maxBufferLength Maximum output buffering size for each iteration
27 public function emit(ResponseInterface $response, $maxBufferLength = 8192)
29 $this->assertNoPreviousOutput();
30 $this->emitHeaders($response);
31 $this->emitStatusLine($response);
33 $range = $this->parseContentRange($response->getHeaderLine('Content-Range'));
35 if (is_array($range) && $range[0] === 'bytes') {
36 $this->emitBodyRange($range, $response, $maxBufferLength);
40 $this->emitBody($response, $maxBufferLength);
44 * Emit the message body.
46 * @param ResponseInterface $response
47 * @param int $maxBufferLength
49 private function emitBody(ResponseInterface $response, $maxBufferLength)
51 $body = $response->getBody();
53 if ($body->isSeekable()) {
57 if (! $body->isReadable()) {
62 while (! $body->eof()) {
63 echo $body->read($maxBufferLength);
68 * Emit a range of the message body.
71 * @param ResponseInterface $response
72 * @param int $maxBufferLength
74 private function emitBodyRange(array $range, ResponseInterface $response, $maxBufferLength)
76 list($unit, $first, $last, $length) = $range;
78 $body = $response->getBody();
80 $length = $last - $first + 1;
82 if ($body->isSeekable()) {
88 if (! $body->isReadable()) {
89 echo substr($body->getContents(), $first, $length);
95 while ($remaining >= $maxBufferLength && ! $body->eof()) {
96 $contents = $body->read($maxBufferLength);
97 $remaining -= strlen($contents);
102 if ($remaining > 0 && ! $body->eof()) {
103 echo $body->read($remaining);
108 * Parse content-range header
109 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16
111 * @param string $header
112 * @return false|array [unit, first, last, length]; returns false if no
113 * content range or an invalid content range is provided
115 private function parseContentRange($header)
117 if (preg_match('/(?P<unit>[\w]+)\s+(?P<first>\d+)-(?P<last>\d+)\/(?P<length>\d+|\*)/', $header, $matches)) {
120 (int) $matches['first'],
121 (int) $matches['last'],
122 $matches['length'] === '*' ? '*' : (int) $matches['length'],