From df150f0d860dbc2311e5e2fcb2fac36ee52db56b Mon Sep 17 00:00:00 2001 From: vlw Date: Wed, 20 Nov 2024 10:39:33 +0000 Subject: [PATCH] feat: add method to validate and return `Reflect\Response` if `Ruleset` is invalid to the `Ruleset` class (#16) Closes #13 Reviewed-on: https://codeberg.org/reflect/reflect-rules-plugin/pulls/16 Co-authored-by: vlw Co-committed-by: vlw --- README.md | 2 ++ src/Ruleset.php | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/README.md b/README.md index 5c956c8..598b880 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,8 @@ Ruleset->get_errors(); Use `Ruleset->is_valid(): bool` to quickly check if any errors are set. +You can also use `Ruleset->validate_or_exit(): true|Response` to automatically return a `Reflect\Response` with all errors to current STDOUT if validation fails. + # Installation Install with composer diff --git a/src/Ruleset.php b/src/Ruleset.php index dc7ff3e..ec5ffa7 100644 --- a/src/Ruleset.php +++ b/src/Ruleset.php @@ -4,6 +4,8 @@ use \ReflectRules\Rules; + use \Reflect\Response; + require_once "Rules.php"; // Available superglobal scopes @@ -169,4 +171,9 @@ return $this->is_valid; } + + // Return Reflect\Response with errors and code 422 Unprocessable Content if validation failed + public function validate_or_exit(): true|Response { + return $this->is_valid() ? true : new Response($this->errors, 422); + } } \ No newline at end of file