Skip to content

Commit

Permalink
New: Ability to run global validators after field validation. Previously
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
AllanJard committed Oct 21, 2024
1 parent 03fe91a commit ba19aae
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion Editor.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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;
}

Expand All @@ -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) {

Check failure on line 892 in Editor.php

View workflow job for this annotation

GitHub Actions / Unit (latest, StaticAnalysis)

Call to function is_bool() with bool will always evaluate to true.
return $this->_getSet($this->_validatorAfterFields, $_, true);
}

// Argument shift
$_ = $afterFields;
return $this->_getSet($this->_validator, $_, true);
}

Expand Down

0 comments on commit ba19aae

Please sign in to comment.