2
0
Web/context.php
2025-09-10 21:30:50 -05:00

96 lines
2.3 KiB
PHP

<?php
/**
* Context holds the request, response, and shared state for a request
*/
class Context
{
public Request $request;
public Response $response;
public array $state = [];
/**
* __construct creates a new Context with request and response
*/
public function __construct()
{
$this->request = new Request();
$this->response = new Response();
}
/**
* set stores a value in the context state
*/
public function set(string $key, mixed $value): void
{
$this->state[$key] = $value;
}
/**
* get retrieves a value from the context state
*/
public function get(string $key): mixed
{
return $this->state[$key] ?? null;
}
/**
* json sends a JSON response
*/
public function json(mixed $data, int $status = 200): void
{
$this->response->json($data, $status)->send();
}
/**
* text sends a plain text response
*/
public function text(string $text, int $status = 200): void
{
$this->response->text($text, $status)->send();
}
/**
* html sends an HTML response
*/
public function html(string $html, int $status = 200): void
{
$this->response->html($html, $status)->send();
}
/**
* redirect sends a redirect response
*/
public function redirect(string $url, int $status = 302): void
{
$this->response->redirect($url, $status)->send();
}
/**
* error sends an error response with appropriate content type
*/
public function error(int $status, string $message = ''): void
{
$messages = [
400 => 'Bad Request',
401 => 'Unauthorized',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
500 => 'Internal Server Error',
502 => 'Bad Gateway',
503 => 'Service Unavailable'
];
$message = $message ?: ($messages[$status] ?? 'Error');
$this->response->status($status);
if ($this->request->header('accept') && str_contains($this->request->header('accept'), 'application/json')) {
$this->json(['error' => $message], $status);
} else {
$this->text($message, $status);
}
}
}