statusCode = $code; return $this; } /** * Set a header for the response */ public function header(string $name, string $value): Response { $this->headers[$name] = $value; return $this; } /** * Set a JSON response with the given data and status code */ public function json(mixed $data, int $status = 200): Response { $this->statusCode = $status; $this->headers['Content-Type'] = 'application/json'; $this->body = json_encode($data); return $this; } /** * Set a text response with the given text and status code */ public function text(string $text, int $status = 200): Response { $this->statusCode = $status; $this->headers['Content-Type'] = 'text/plain'; $this->body = $text; return $this; } /** * Set an HTML response with the given HTML and status code */ public function html(string $html, int $status = 200): Response { $this->statusCode = $status; $this->headers['Content-Type'] = 'text/html; charset=utf-8'; $this->body = $html; return $this; } /** * Redirect to the given URL with the given status code */ public function redirect(string $url, int $status = 302): Response { $this->statusCode = $status; $this->headers['Location'] = $url; return $this; } /** * Set a cookie with the given name, value, and options */ public function cookie(string $name, string $value, array $options = []): Response { $options = array_merge([ 'expires' => 0, 'path' => '/', 'domain' => '', 'secure' => false, 'httponly' => true, 'samesite' => 'Lax' ], $options); setcookie($name, $value, [ 'expires' => $options['expires'], 'path' => $options['path'], 'domain' => $options['domain'], 'secure' => $options['secure'], 'httponly' => $options['httponly'], 'samesite' => $options['samesite'] ]); return $this; } /** * Send the response to the client */ public function send(): void { if ($this->sent) { return; } http_response_code($this->statusCode); foreach ($this->headers as $name => $value) { header("$name: $value"); } echo $this->body; $this->sent = true; } /** * Write the given content to the response body */ public function write(string $content): Response { $this->body .= $content; return $this; } /** * End the response with the given content */ public function end(string $content = ''): void { if ($content) { $this->body .= $content; } $this->send(); } }