about summary refs log tree commit diff stats
path: root/classes/Response.php
blob: e45814b93b83b90b0774a08272b2236a20c14d3d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php

class Response
{
    private int $status = 200;
    /** @var array<string, string> */
    private array $headers = [];
    private string $body = '';
    private string $contentType = "application/json";

    public function withStatus(int $code, string $reasonPhrase = ''): self
    {
        $clone = clone $this;
        $clone->status = $code;
        return $clone;
    }

    public function withHeader(string $name, string $value): self
    {
        $clone = clone $this;
        $clone->headers[$name] = $value;
        return $clone;
    }

    public function getBody(): string
    {
        return $this->body;
    }

    public function withBody(string $body): self
    {
        $clone = clone $this;
        $clone->body = $body;
        return $clone;
    }

    public function send(): void
    {
        $contentTypeFound = false;

        if ($this->headers) {
            foreach ($this->headers as $name => $value) {
                header("$name: $value");

                if (strtolower($name) === "content-type")
                    $contentTypeFound = true;
            }
        }

        if (!$contentTypeFound)
            header("Content-type: {$this->contentType}");

        header("X-Content-Type-Options: nosniff");

        http_response_code($this->status);
        echo $this->body;
    }
}