Passed
Pull Request — master (#661)
by Maxim
18:05
created

SapiEmitter::assertNoPreviousOutput()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 4
nc 3
nop 0
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 *
9
 * @see       https://github.com/zendframework/zend-httphandlerrunner for the canonical source repository
10
 * @copyright Copyright (c) 2018 Zend Technologies USA Inc. (https://www.zend.com)
11
 * @license   https://github.com/zendframework/zend-httphandlerrunner/blob/master/LICENSE.md New BSD License
12
 */
13
14
declare(strict_types=1);
15
16
namespace Spiral\Http\Emitter;
17
18
use Psr\Http\Message\ResponseInterface;
19
use Spiral\Http\Config\HttpConfig;
20
use Spiral\Http\EmitterInterface;
21
use Spiral\Http\Exception\EmitterException;
22
23
/**
24
 * Source code has been extracted from Zend/Diactoros.
25
 */
26
final class SapiEmitter implements EmitterInterface
27
{
28
    /**
29
     * @var positive-int Preferred chunk size to be read from the stream before emitting.
0 ignored issues
show
Documentation Bug introduced by
The doc comment positive-int at position 0 could not be parsed: Unknown type name 'positive-int' at position 0 in positive-int.
Loading history...
30
     */
31
    public int $bufferSize = 2_097_152; // 2MB
0 ignored issues
show
Bug introduced by
The constant Spiral\Http\Emitter\2_097_152 was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
32
33 10
    public function __construct(HttpConfig $config)
34
    {
35 10
        if (($chunkSize = $config->getChunkSize()) !== null) {
36 1
            $this->bufferSize = $chunkSize;
37
        }
38
    }
39
40
    /**
41
     * Emits a response for a PHP SAPI environment.
42
     *
43
     * Emits the status line and headers via the header() function, and the
44
     * body content via the output buffer.
45
     *
46
     * @param ResponseInterface $response
47
     */
48 8
    public function emit(ResponseInterface $response): bool
49
    {
50 8
        $this->assertNoPreviousOutput();
51
52 6
        $this->emitHeaders($response);
53 6
        $this->emitStatusLine($response);
54 6
        $this->emitBody($response);
55
56 6
        return true;
57
    }
58
59
    /**
60
     * Emit the message body.
61
     */
62 6
    private function emitBody(ResponseInterface $response): void
63
    {
64 6
        $body = $response->getBody();
65 6
        if ($body->isSeekable()) {
66 5
            $body->rewind();
67
        }
68 6
        if (!$body->isReadable()) {
69 1
            return;
70
        }
71 5
        while (!$body->eof()) {
72 5
            echo $body->read($this->bufferSize);
73 5
            flush();
74
        }
75
    }
76
77
    /**
78
     * Checks to see if content has previously been sent.
79
     *
80
     * If either headers have been sent or the output buffer contains content,
81
     * raises an exception.
82
     *
83
     * @throws EmitterException if headers have already been sent.
84
     * @throws EmitterException if output is present in the output buffer.
85
     */
86 8
    private function assertNoPreviousOutput(): void
87
    {
88 8
        if (headers_sent()) {
89 1
            throw new EmitterException('Unable to emit response, headers already send.');
90
        }
91
92 7
        if (ob_get_level() > 0 && ob_get_length() > 0) {
93 1
            throw new EmitterException('Unable to emit response, found non closed buffered output.');
94
        }
95
    }
96
97
    /**
98
     * Emit the status line.
99
     *
100
     * Emits the status line using the protocol version and status code from
101
     * the response; if a reason phrase is available, it, too, is emitted.
102
     *
103
     * It is important to mention that this method should be called after
104
     * `emitHeaders()` in order to prevent PHP from changing the status code of
105
     * the emitted response.
106
     *
107
     * @param ResponseInterface $response
108
     */
109 6
    private function emitStatusLine(ResponseInterface $response): void
110
    {
111 6
        $reasonPhrase = $response->getReasonPhrase();
112 6
        $statusCode = $response->getStatusCode();
113
114 6
        header(sprintf(
115
            'HTTP/%s %d%s',
116 6
            $response->getProtocolVersion(),
117
            $statusCode,
118 6
            ($reasonPhrase ? ' ' . $reasonPhrase : '')
119
        ), true, $statusCode);
120
    }
121
122
    /**
123
     * Emit response headers.
124
     *
125
     * Loops through each header, emitting each; if the header value
126
     * is an array with multiple values, ensures that each is sent
127
     * in such a way as to create aggregate headers (instead of replace
128
     * the previous).
129
     *
130
     * @param ResponseInterface $response
131
     */
132 6
    private function emitHeaders(ResponseInterface $response): void
133
    {
134 6
        $statusCode = $response->getStatusCode();
135
136 6
        foreach ($response->getHeaders() as $header => $values) {
137 5
            $name = $this->filterHeader($header);
138 5
            $first = $name === 'Set-Cookie' ? false : true;
139 5
            foreach ($values as $value) {
140 5
                header(sprintf(
141
                    '%s: %s',
142
                    $name,
143
                    $value
144
                ), $first, $statusCode);
145 5
                $first = false;
146
            }
147
        }
148
    }
149
150
    /**
151
     * Filter a header name to wordcase
152
     */
153 5
    private function filterHeader(string $header): string
154
    {
155 5
        return ucwords($header, '-');
156
    }
157
}
158