Passed
Pull Request — master (#139)
by Zhukov
01:48
created

SapiEmitter::shouldOutputBody()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

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
ccs 2
cts 2
cp 1
crap 1
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 2
    public function emit(ResponseInterface $response, bool $withoutBody = false): bool
15
    {
16 2
        $status = $response->getStatusCode();
17
18 2
        header_remove();
19 2
        foreach ($response->getHeaders() as $header => $values) {
20 2
            foreach ($values as $value) {
21 2
                header(sprintf(
22 2
                    '%s: %s',
23 2
                    $header,
24 2
                    $value
25 2
                ), $header !== 'Set-Cookie', $status);
26
            }
27
        }
28
29 2
        $reason = $response->getReasonPhrase();
30
31 2
        header(sprintf(
32 2
            'HTTP/%s %d%s',
33 2
            $response->getProtocolVersion(),
34 2
            $status,
35 2
            ($reason !== '' ? ' ' . $reason : '')
36 2
        ), true, $status);
37
38 2
        if ($withoutBody === false && $this->shouldOutputBody($response)) {
39 1
            $contentLength = $response->getBody()->getSize();
40 1
            if ($response->hasHeader('Content-Length')) {
41
                $contentLengthHeader = $response->getHeader('Content-Length');
42
                $contentLength = array_shift($contentLengthHeader);
43
            }
44
45 1
            header(sprintf('Content-Length: %s', $contentLength), true, $status);
46
47 1
            echo $response->getBody();
48
        }
49
50 2
        return true;
51
    }
52
53 2
    private function shouldOutputBody(ResponseInterface $response): bool
54
    {
55 2
        return !\in_array($response->getStatusCode(), self::NO_BODY_RESPONSE_CODES, true);
56
    }
57
}
58