about summary refs log tree commit diff stats
path: root/classes/Response.php
blob: dcbbc5b714eecdcdcbd15142c5c62d032ebc33e1 (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
<?php

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

    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
    {
        if ($this->headers) {
            foreach ($this->headers as $name => $value) {
                header("$name: $value");
            }
        }
        http_response_code($this->status);
        echo $this->body;
    }
}