2
0
Web/Context.php

131 lines
3.2 KiB
PHP

<?php
require_once __DIR__ . '/Session.php';
require_once __DIR__ . '/Validator.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);
}
}
/**
* validate validates input data against rules
*/
public function validate(array $data, array $rules, array $messages = []): Validator
{
$validator = new Validator();
$validator->validate($data, $rules, $messages);
if ($validator->failed()) {
throw new ValidationException($validator->errors());
}
return $validator;
}
/**
* validateRequest validates request data against rules
*/
public function validateRequest(array $rules, array $messages = []): Validator
{
$data = array_merge(
$this->request->query,
$this->request->body,
$this->request->params
);
return $this->validate($data, $rules, $messages);
}
}