From ba19aaeab1e6d9bca0d295c51bb513345681a575 Mon Sep 17 00:00:00 2001 From: Allan Jardine Date: Mon, 21 Oct 2024 14:56:24 +0000 Subject: [PATCH] New: Ability to run global validators after field validation. Previously the global validator would run before the field validation, but now it is possible to also run validators after. This is done by passing `true` as the first argument to the `Editor->validator()` method and then the validation function as the second parameter. The original behaviour is maintained when either `false` is given as the first parameter, or if the validation function is given as the first parameter. --- Editor.php | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/Editor.php b/Editor.php index 7898e78..be6607c 100644 --- a/Editor.php +++ b/Editor.php @@ -205,6 +205,9 @@ public function __construct($db = null, $table = null, $pkey = null) /** @var array */ private $_validator = []; + /** @var array */ + private $_validatorAfterFields = []; + /** @var bool Enable true / catch when processing */ private $_tryCatch = true; @@ -856,6 +859,18 @@ public function validate(&$errors, $data) } } + // Global validators to run _after_ field validation + for ($i = 0; $i < count($this->_validatorAfterFields); ++$i) { + $validator = $this->_validatorAfterFields[$i]; + $ret = $validator($this, $this->_actionName, $data); + + if (is_string($ret)) { + $this->_out['error'] = $ret; + + return false; + } + } + return count($errors) > 0 ? false : true; } @@ -864,14 +879,22 @@ public function validate(&$errors, $data) * and remove actions performed from the client-side. Multiple validators * can be added. * + * @param bool $afterFields `true` to run the validator after field validation, + * `false` to run before. Can be omitted (which is the equivalent of `false`). * @param callable($this, self::ACTION_*, array): ?string $_ Function to execute when validating the input data. * It is passed three parameters: 1. The editor instance, 2. The action * and 3. The values. * * @return ($_ is null ? callable : $this) The validator function. */ - public function validator($_ = null) + public function validator($afterFields, $_ = null) { + if (is_bool($afterFields) && $afterFields === true) { + return $this->_getSet($this->_validatorAfterFields, $_, true); + } + + // Argument shift + $_ = $afterFields; return $this->_getSet($this->_validator, $_, true); }