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

Emitter::emit()   C

Complexity

Conditions 12
Paths 48

Size

Total Lines 40
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 24
c 1
b 0
f 0
nc 48
nop 0
dl 0
loc 40
rs 6.9666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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