Passed
Branch release (695ec7)
by Henry
04:31
created

Emitter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
/**
3
 * This file is part of the Divergence package.
4
 *
5
 * (c) Henry Paradiz <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace Divergence\Responders;
11
12
use Psr\Http\Message\ResponseInterface;
13
14
class Emitter
15
{
16
    protected ResponseInterface $response;
17
18
    public function __construct(ResponseInterface $response)
19
    {
20
        $this->response = $response;
21
    }
22
23
    /**
24
     * Forked from Slim
25
     *
26
     * @return void
27
     */
28
    public function emit()
29
    {
30
        if (!headers_sent()) {
31
            foreach ($this->response->getHeaders() as $name => $values) {
32
                foreach ($values as $value) {
33
                    header(sprintf('%s: %s', $name, $value), false);
34
                }
35
            }
36
37
            // should come last just in case
38
            header(sprintf('HTTP/%s %s %s', $this->response->getProtocolVersion(), $this->response->getStatusCode(), $this->response->getReasonPhrase()));
39
        }
40
41
        $body = $this->response->getBody();
42
        if ($body->isSeekable()) {
43
            $body->rewind(); // just in case
44
        }
45
46
        $contentLength = $this->response->getHeaderLine('Content-Length');
47
        if (!$contentLength) {
48
            $contentLength = $body->getSize();
49
        }
50
51
        if (isset($contentLength)) {
52
            $amountToRead = $contentLength;
53
            while ($amountToRead > 0 && !$body->eof()) {
54
                $data = $body->read(min(4096, $amountToRead));
55
                echo $data;
56
57
                $amountToRead -= strlen($data);
58
59
                if (connection_status() != CONNECTION_NORMAL) {
60
                    break;
61
                }
62
            }
63
        } else {
64
            while (!$body->eof()) {
65
                echo $body->read(4096);
66
                if (connection_status() != CONNECTION_NORMAL) {
67
                    break;
68
                }
69
            }
70
        }
71
    }
72
}
73