diff options
| author | David T. Sadler <davidtsadler@googlemail.com> | 2026-08-09 20:04:39 +0100 |
|---|---|---|
| committer | David T. Sadler <davidtsadler@googlemail.com> | 2026-08-09 20:04:39 +0100 |
| commit | b9c4f1dcf1333c14e2d1b67561ec7a5f955baa6e (patch) | |
| tree | 610536953be739d0778f19c90c477f080a24718a /src/Response.php | |
Diffstat (limited to 'src/Response.php')
| -rw-r--r-- | src/Response.php | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/src/Response.php b/src/Response.php new file mode 100644 index 0000000..d3c4f69 --- /dev/null +++ b/src/Response.php @@ -0,0 +1,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; + } +} |
