101 lines
2.4 KiB
PHP
101 lines
2.4 KiB
PHP
<?php
|
|
|
|
require_once __DIR__ . '/session.php';
|
|
|
|
/**
|
|
* Context holds the request, response, and shared state for a request
|
|
*/
|
|
class Context
|
|
{
|
|
public Request $request;
|
|
public Response $response;
|
|
public Session $session;
|
|
public array $state = [];
|
|
|
|
/**
|
|
* __construct creates a new Context with request and response
|
|
*/
|
|
public function __construct()
|
|
{
|
|
$this->request = new Request();
|
|
$this->response = new Response();
|
|
$this->session = new Session();
|
|
$this->session->start();
|
|
}
|
|
|
|
/**
|
|
* 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);
|
|
}
|
|
}
|
|
}
|