2
0

add validator, error handler

This commit is contained in:
Sky Johnson 2025-09-10 21:47:17 -05:00
parent dbbf3b8f4f
commit fc391879d0
2 changed files with 49 additions and 5 deletions

View File

@ -1,6 +1,7 @@
<?php
require_once __DIR__ . '/session.php';
require_once __DIR__ . '/validator.php';
/**
* Context holds the request, response, and shared state for a request
@ -97,4 +98,33 @@ class Context
$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);
}
}

24
web.php
View File

@ -5,6 +5,7 @@ require_once __DIR__ . '/request.php';
require_once __DIR__ . '/response.php';
require_once __DIR__ . '/context.php';
require_once __DIR__ . '/router.php';
require_once __DIR__ . '/errorhandler.php';
/**
* Web is the application controller itself
@ -14,10 +15,12 @@ class Web
private Router $router;
private array $middleware = [];
private Context $context;
private ErrorHandler $errorHandler;
public function __construct()
public function __construct(bool $debug = false)
{
$this->router = new Router();
$this->errorHandler = new ErrorHandler($debug);
}
public function use(callable $middleware): self
@ -84,6 +87,18 @@ class Web
return $this;
}
public function setErrorHandler(int $status, callable $handler): self
{
$this->errorHandler->register($status, $handler);
return $this;
}
public function setDefaultErrorHandler(callable $handler): self
{
$this->errorHandler->setDefaultHandler($handler);
return $this;
}
private function addGroupRoutes(Router $router, string $prefix, string $path, mixed $node, string $currentPath = ''): void
{
if ($path !== '') $currentPath = $currentPath ? "$currentPath/$path" : $path;
@ -113,12 +128,12 @@ class Web
);
if ($result['code'] === 404) {
$this->context->error(404);
$this->errorHandler->handle($this->context, 404);
return;
}
if ($result['code'] === 405) {
$this->context->error(405);
$this->errorHandler->handle($this->context, 405);
return;
}
@ -151,8 +166,7 @@ class Web
$chain();
} catch (Exception $e) {
error_log($e->getMessage());
$this->context->error(500, 'Internal Server Error');
$this->errorHandler->handleException($this->context, $e);
}
}
}