From fc391879d0d823844ddf547c737b8a6f923e92dd Mon Sep 17 00:00:00 2001 From: Sky Johnson Date: Wed, 10 Sep 2025 21:47:17 -0500 Subject: [PATCH] add validator, error handler --- context.php | 30 ++++++++++++++++++++++++++++++ web.php | 24 +++++++++++++++++++----- 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/context.php b/context.php index bfe31ed..10918a8 100644 --- a/context.php +++ b/context.php @@ -1,6 +1,7 @@ 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); + } } diff --git a/web.php b/web.php index 44b0560..e41e051 100644 --- a/web.php +++ b/web.php @@ -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); } } }