Completed
Push — master ( e4c888...b002ee )
by Alexander
10:41 queued 05:38
created

SapiEmitter::withoutBody()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 5
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Yiisoft\Yii\Web\Emitter;
4
5
use Psr\Http\Message\ResponseInterface;
6
7
/**
8
 * SapiEmitter sends a response using PHP Server API
9
 */
10
final class SapiEmitter implements EmitterInterface
11
{
12
    private const NO_BODY_RESPONSE_CODES = [204, 205, 304];
13
14
    public function emit(ResponseInterface $response, bool $withoutBody = false): bool
15
    {
16
        $status = $response->getStatusCode();
17
18
        header_remove();
19
        foreach ($response->getHeaders() as $header => $values) {
20
            foreach ($values as $value) {
21
                header(sprintf(
22
                    '%s: %s',
23
                    $header,
24
                    $value
25
                ), $header !== 'Set-Cookie', $status);
26
            }
27
        }
28
29
        $reason = $response->getReasonPhrase();
30
31
        header(sprintf(
32
            'HTTP/%s %d%s',
33
            $response->getProtocolVersion(),
34
            $status,
35
            ($reason !== '' ? ' ' . $reason : '')
36
        ), true, $status);
37
38
        if ($withoutBody === false && $this->shouldOutputBody($response)) {
39
            $contentLength = $response->getBody()->getSize();
40
            if ($response->hasHeader('Content-Length')) {
41
                $contentLengthHeader = $response->getHeader('Content-Length');
42
                $contentLength = array_shift($contentLengthHeader);
43
            }
44
45
            header(sprintf('Content-Length: %s', $contentLength), true, $status);
46
47
            echo $response->getBody();
48
        }
49
50
        return true;
51
    }
52
53
    private function shouldOutputBody(ResponseInterface $response): bool
54
    {
55
        return !\in_array($response->getStatusCode(), self::NO_BODY_RESPONSE_CODES, true);
56
    }
57
}
58