You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
1.0 KiB
34 lines
1.0 KiB
<?php
|
|
|
|
namespace IQBall\Core\Validation;
|
|
|
|
/**
|
|
* A simple validator that takes a predicate and an error factory
|
|
*/
|
|
class SimpleFunctionValidator extends Validator {
|
|
/**
|
|
* @var callable(mixed): bool
|
|
*/
|
|
private $predicate;
|
|
/**
|
|
* @var callable(string): ValidationFail[]
|
|
*/
|
|
private $errorFactory;
|
|
|
|
/**
|
|
* @param callable(mixed): bool $predicate a function predicate with signature: `(string) => bool`, to validate the given string
|
|
* @param callable(string): ValidationFail[] $errorsFactory a factory function with signature `(string) => array` to emit failures when the predicate fails
|
|
*/
|
|
public function __construct(callable $predicate, callable $errorsFactory) {
|
|
$this->predicate = $predicate;
|
|
$this->errorFactory = $errorsFactory;
|
|
}
|
|
|
|
public function validate(string $name, $val): array {
|
|
if (!call_user_func_array($this->predicate, [$val])) {
|
|
return call_user_func_array($this->errorFactory, [$name]);
|
|
}
|
|
return [];
|
|
}
|
|
}
|