summaryrefslogtreecommitdiff
path: root/src/Response.php
blob: d3c4f6914f1b841e714fd3f1dbc39be78b4ff0d5 (plain)
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
<?php

declare(strict_types=1);

namespace TCB;

final class Response
{
    /**
     * @param array<string, string> $headers Key-value pairs of additional HTTP headers
     */
    public function __construct(
        public readonly int $statusCode,
        public readonly string $contentType,
        public readonly string $body,
        public readonly array $headers = [],
    ) {}

    public function __toString(): string
    {
        $reason = match ($this->statusCode) {
            200 => 'OK',
            400 => 'Bad Request',
            401 => 'Unauthorized',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            500 => 'Internal Server Error',
            default => '',
        };

        $statusLine = trim("HTTP/1.1 {$this->statusCode} {$reason}");
        $contentLength = strlen($this->body);

        // Build base headers.
        $formattedHeaders = [
            $statusLine,
            "Content-Type: $this->contentType",
            "Content-Length: $contentLength",
            "Connection: close",
        ];

        // Format and append custom headers.
        foreach ($this->headers as $name => $value) {
            $formattedHeaders[] = "$name: $value";
        }

        return implode("\r\n", $formattedHeaders) . "\r\n\r\n" . $this->body;
    }
}