Completed
Pull Request — master (#139)
by Zhukov
02:04
created

SapiEmitter   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 27
c 4
b 0
f 0
dl 0
loc 46
rs 10
ccs 27
cts 27
cp 1
wmc 8

2 Methods

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