Response   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 25
c 3
b 0
f 0
dl 0
loc 67
rs 10
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A sendContent() 0 3 1
A sendHeaders() 0 25 3
A send() 0 9 3
A __construct() 0 11 2
1
<?php
2
3
namespace pjpawel\LightApi\Http;
4
5
use function function_exists;
6
7
class Response
8
{
9
10
    public string $content;
11
    public ResponseStatus $status;
12
    public HeadersBag $headers;
13
    public string $version;
14
15
    public function __construct(string|array $content = '', ResponseStatus $status = ResponseStatus::OK, array $headers = [], $version = '1.0')
16
    {
17
        $this->status = $status;
18
        $this->headers = new HeadersBag($headers);
19
        $this->version = $version;
20
        if (is_string($content)) {
21
            $this->content = $content;
22
            $this->headers->add('Content-Type', 'text/html');
23
        } else {
24
            $this->content = json_encode($content);
25
            $this->headers->add('Content-Type', 'application/json');
26
        }
27
    }
28
29
    public function send(): void
30
    {
31
        $this->sendHeaders();
32
        $this->sendContent();
33
34
        if (function_exists('fastcgi_finish_request')) {
35
            fastcgi_finish_request();
36
        } elseif (function_exists('litespeed_finish_request')) {
37
            litespeed_finish_request();
38
        } /*elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
39
            static::closeOutputBuffers(0, true);
40
            flush();
41
        }*/
42
    }
43
44
    private function sendHeaders(): void
45
    {
46
        if (headers_sent()) {
47
            return;
48
        }
49
50
        foreach ($this->headers->parameters as $key => $value) {
51
            header($key . ': ' . $value, true, $this->status->value);
52
        }
53
54
        /*foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) {
55
            //TODO: change
56
            $replace = 0 === strcasecmp($name, 'Content-Type');
57
            foreach ($values as $value) {
58
                header($name.': '.$value, $replace, $this->status->value);
59
            }
60
        }
61
62
        foreach ($this->headers->getCookies() as $cookie) {
63
            //TODO:
64
            header('Set-Cookie: '.$cookie, false, $this->status->value);
65
        }*/
66
67
        // status
68
        header(sprintf('HTTP/%s %s %s', $this->version, $this->status->value, $this->status->getText()), true, $this->status->value);
69
    }
70
71
    private function sendContent(): void
72
    {
73
        echo $this->content;
74
    }
75
}