2
0
Web/Response.php

152 lines
3.1 KiB
PHP

<?php
namespace Web;
require_once __DIR__ . '/Cookies.php';
/**
* Response class represents an HTTP response
*/
class Response
{
private int $statusCode = 200;
private array $headers = [];
private string $body = '';
private bool $sent = false;
private ?Cookies $cookie = null;
/**
* Set the cookie manager for this response
*/
public function setCookieManager(Cookies $cookie): Response
{
$this->cookie = $cookie;
return $this;
}
/**
* Set the HTTP status code for the response
*/
public function status(int $code): Response
{
$this->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
{
if ($this->cookie) {
$this->cookie->set($name, $value, $options);
} else {
// Fallback to direct setcookie if no Cookie manager is set
$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();
}
}