This commit is contained in:
2023-12-18 15:01:09 +08:00
parent d860269a7c
commit 645d73453c
15 changed files with 251 additions and 613 deletions
+4 -8
View File
@@ -18,19 +18,15 @@ class ArrayValidator extends BaseValidator
{ {
/** /**
* @param string $field
* @param mixed $value
* @return bool * @return bool
* *
* 检查 * 检查
*/ */
public function trigger(): bool public function trigger(string $field, mixed $value): bool
{ {
return $this->_validator($this->field, function ($field, $params) { return is_array($value);
$value = $params[$field] ?? null;
if (!is_array($value)) {
return $this->addError($field, 'The param :attribute must a array');
}
return true;
}, $this->params);
} }
} }
+7 -110
View File
@@ -5,6 +5,7 @@ namespace validator;
use Database\Model; use Database\Model;
use Database\ModelInterface;
use Exception; use Exception;
@@ -14,87 +15,23 @@ use Exception;
abstract class BaseValidator abstract class BaseValidator
{ {
public array $field = []; public mixed $value;
public array $rules = [];
public string $method; protected string $message;
protected bool $isFail = TRUE;
protected string $message = '';
protected array $params = [];
protected ?Model $model = null;
/** /**
* @param $model * @param string $field
*/ * @param float $value
public function setModel($model): void
{
$this->model = $model;
}
/**
* @return Model|null
*/
public function getModel(): ?Model
{
return $this->model;
}
/**
* BaseValidator constructor.
* @param array $config
*/
public function __construct(array $config = [])
{
$this->regConfig($config);
}
/**
* @param $config
*/
private function regConfig($config): void
{
if (count($config) < 1) {
return;
}
foreach ($config as $key => $val) {
$this->$key = $val;
}
}
/**
* @return bool * @return bool
* @throws * @throws Exception
*/ */
public function trigger(): bool public function trigger(string $field, mixed $value): bool
{ {
throw new Exception('Child Class must define method of trigger'); throw new Exception('Child Class must define method of trigger');
} }
/**
* @return array
*/
protected function getParams(): array
{
return $this->params;
}
/**
* @param array $data
* @return $this
*/
public function setParams(array $data): static
{
$this->params = $data;
return $this;
}
/** /**
* @param $field * @param $field
@@ -103,37 +40,14 @@ abstract class BaseValidator
*/ */
public function addError($field, $message): bool public function addError($field, $message): bool
{ {
$this->isFail = FALSE;
if (!is_null($field)) { if (!is_null($field)) {
$message = str_replace(':attribute', $field, $message); $message = str_replace(':attribute', $field, $message);
} }
\trigger_print_error($message, "mysql");
$this->message = $message; $this->message = $message;
return $this->isFail;
}
/**
* @param string|array $fields
* @param callable $callback
* @param ...$params
* @return bool
*/
protected function _validator(string|array $fields, callable $callback, ...$params): bool
{
if (is_string($fields)) {
$fields = [$fields];
}
foreach ($fields as $field) {
if (!$callback($field, ...$params)) {
return false; return false;
} }
}
return true;
}
/** /**
@@ -143,21 +57,4 @@ abstract class BaseValidator
{ {
return $this->message; return $this->message;
} }
/**
* @param $name
* @param $value
* @throws
*/
public function __set($name, $value)
{
$method = 'set' . ucfirst($name);
if (method_exists($this, $method)) {
$this->$method($value);
} else if (property_exists($this, $name)) {
$this->$name = $value;
} else {
throw new Exception('unknown property ' . $name . ' in class ' . static::class);
}
}
} }
+16 -56
View File
@@ -21,104 +21,64 @@ class DateTimeValidator extends BaseValidator
public string $method; public string $method;
/** /**
* @param string $field
* @param mixed $value
* @return bool * @return bool
*/ */
public function trigger(): bool public function trigger(string $field, mixed $value): bool
{ {
return $this->_validator($this->field, function ($field, $params, $method) {
$value = $params[$field] ?? null; $value = $params[$field] ?? null;
return match ($method) { return match ($this->method) {
self::DATE => $this->validatorDate($field, $value), self::DATE => $this->validatorDate($value),
self::DATE_TIME => $this->validateDatetime($field, $value), self::DATE_TIME => $this->validateDatetime($value),
self::TIME => $this->validatorTime($field, $value), self::TIME => $this->validatorTime($value),
self::STR_TO_TIME => $this->validatorTimestamp($field, $value), self::STR_TO_TIME => $this->validatorTimestamp($value),
default => true, default => true,
}; };
}, $this->params, strtolower($this->method));
} }
/** /**
* @param $field
* @param $value * @param $value
* @return bool * @return bool
* *
* 效验分秒 格式如 01:02 or 01-02 * 效验分秒 格式如 01:02 or 01-02
*/ */
public function validatorTime($field, $value): bool public function validatorTime($value): bool
{ {
if (!is_string($value)) { return (bool)preg_match('/^\d{2}:\d{2}(:\d{2})?+(\.\d+)?$/', $value);
return $this->addError($field, 'The param :attribute not is a date value');
}
$match = preg_match('/^[0-5]?\d{1}.{1}[0-5]?\d{1}$/', $value, $result);
if ($match && $result[0] == $value) {
return true;
} else {
return $this->addError($field, 'The param :attribute format error');
}
} }
/** /**
* @param $field
* @param $value * @param $value
* @return bool * @return bool
* *
* 效验分秒 格式如 2017-12-22 01:02 * 效验分秒 格式如 2017-12-22 01:02
*/ */
public function validateDatetime($field, $value): bool public function validateDatetime($value): bool
{ {
if (!is_string($value)) { return (bool)preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?+(\.\d+)?$/', $value);
return $this->addError($field, 'The param :attribute not is a date value');
}
$match = '/^\d{4}\-\d{2}\-\d{2}\s+\d{2}:\d{2}:\d{2}$/';
$match = preg_match($match, $value, $result);
if ($match && $result[0] == $value) {
return true;
} else {
return $this->addError($field, 'The param :attribute format error');
}
} }
/** /**
* @param $field
* @param $value * @param $value
* @return bool * @return bool
* *
* 效验分秒 格式如 2017-12-22 * 效验分秒 格式如 2017-12-22
*/ */
public function validatorDate($field, $value): bool public function validatorDate($value): bool
{ {
if (!is_string($value)) { return (bool)preg_match('/^\d{4}-\d{2}-\d{2}$/', $value);
return $this->addError($field, 'The param :attribute not is a date value');
}
$match = preg_match('/^(\d{4}).*([0-12]).*([0-31]).*$/', $value, $result);
if ($match && $result[0] == $value) {
return true;
} else {
return $this->addError($field, 'The param :attribute format error');
}
} }
/** /**
* @param $field
* @param $value * @param $value
* @return bool * @return bool
* *
* 效验时间戳 格式如 1521452254 * 效验时间戳 格式如 1521452254
*/ */
public function validatorTimestamp($field, $value): bool public function validatorTimestamp($value): bool
{ {
if (!is_numeric($value)) { return (bool)preg_match('/^1\d{9}$/', $value);
return $this->addError($field, 'The param :attribute not is a timestamp value');
}
if (strlen((string)$value) != 10) {
return $this->addError($field, 'The param :attribute not is a timestamp value');
}
if (!date('YmdHis', $value)) {
return $this->addError($field, 'The param :attribute format error');
}
return true;
} }
} }
+4 -8
View File
@@ -16,18 +16,14 @@ class EmailValidator extends BaseValidator
{ {
/** /**
* @param string $field
* @param mixed $value
* @return bool * @return bool
* 检查是否存在 * 检查是否存在
*/ */
public function trigger(): bool public function trigger(string $field, mixed $value): bool
{ {
return $this->_validator($this->field, function ($field, $params) { return filter_var($value, FILTER_VALIDATE_EMAIL);
$value = $params[$field] ?? null;
if (!filter_var($value,FILTER_VALIDATE_EMAIL)) {
return $this->addError($field,'The param :attribute format error');
}
return true;
}, $this->params);
} }
} }
+8 -11
View File
@@ -27,21 +27,18 @@ class EmptyValidator extends BaseValidator
public string $method; public string $method;
/** /**
* @param string $field
* @param mixed $value
* @return bool * @return bool
* *
* 检查参数是否为NULL * 检查参数是否为NULL
*/ */
public function trigger(): bool public function trigger(string $field, mixed $value): bool
{ {
return $this->_validator($this->field, function ($field, $params, $method) { return match ($this->method) {
$value = $params[$field] ?? null; self::CAN_NOT_NULL => !is_null($value),
if ($value === null) { self::CAN_NOT_EMPTY => !empty($value),
return $this->addError($field, 'The :attribute can not null.'); default => true
} };
if (empty($value)) {
return $this->addError($field, 'The :attribute can not empty.');
}
return true;
}, $this->params, strtolower($this->method));
} }
} }
+4 -12
View File
@@ -12,22 +12,14 @@ namespace validator;
class EnumValidator extends BaseValidator class EnumValidator extends BaseValidator
{ {
public array $value = [];
/** /**
* @param string $field
* @param mixed $value
* @return bool * @return bool
*/ */
public function trigger(): bool public function trigger(string $field, mixed $value): bool
{ {
return $this->_validator($this->field, function ($field, $params, $values) { return in_array($value, $this->value);
$value = $params[$field] ?? null;
if (in_array($value, $values)) {
return true;
}
$message = 'The param :attribute value(' . $value . ') only in ' . implode(',', $values);
return $this->addError($field, $message);
}, $this->params, $this->value);
} }
} }
+6 -17
View File
@@ -10,32 +10,21 @@ declare(strict_types=1);
namespace validator; namespace validator;
use Database\ModelInterface;
/** /**
* *
*/ */
class IntegerValidator extends BaseValidator class IntegerValidator extends BaseValidator
{ {
const MIN = 'min';
const MAX = 'max';
public ?int $value = null;
private string $type = '';
/** /**
* @param string $field
* @param float $value
* @return bool * @return bool
*/ */
public function trigger(): bool public function trigger(string $field, mixed $value): bool
{ {
return $this->_validator($this->field, function ($field, $params, $origin, $type) { return (float)$value == $value;
$value = $params[$field] ?? null;
if ($type !== self::MIN && $value < $origin) {
return $this->addError($field,'The ' . $field . ' cannot be less than the default value.');
}
if ($type !== self::MAX && $value > $origin) {
return $this->addError($field,'The ' . $field . ' cannot be greater than the default value.');
}
return true;
}, $this->params, $this->value, $this->type);
} }
} }
+16 -56
View File
@@ -21,89 +21,49 @@ class LengthValidator extends BaseValidator
public int $value; public int $value;
/** /**
* @param string $field
* @param mixed $value
* @return bool * @return bool
*/ */
public function trigger(): bool public function trigger(string $field, mixed $value): bool
{ {
return $this->_validator($this->field, function ($field, $params, $method, $length) { return match ($this->method) {
$value = $params[$field] ?? null; self::MAX_LENGTH => $this->maxLength((string)$value),
return match ($method) { self::MIN_LENGTH => $this->minLength((string)$value),
self::MAX_LENGTH => $this->maxLength($field, (string)$value), default => $this->defaultLength((string)$value),
self::MIN_LENGTH => $this->minLength($field, (string)$value),
default => $this->defaultLength($field, (string)$value),
}; };
}, $this->params, strtolower($this->method), $this->value);
} }
/** /**
* @param $field * @param string $value
* @param $value
* @return bool * @return bool
* *
* 效验长度是否大于最大长度 * 效验长度是否大于最大长度
*/ */
private function maxLength($field, $value): bool private function maxLength(string $value): bool
{ {
if (is_array($value)) { return mb_strlen($value) <= $this->value;
if (count($value) > $value) {
return $this->addError($field, 'The param :attribute length overflow');
}
} else {
if (is_numeric($value) && strlen((string)$value) > $this->value) {
return $this->addError($field, 'The param :attribute length overflow');
}
if (strlen($value) > $this->value) {
return $this->addError($field, 'The param :attribute length overflow');
}
}
return TRUE;
} }
/** /**
* @param $field * @param string $value
* @param $value
* @return bool * @return bool
* *
* 效验长度是否小于最小长度 * 效验长度是否小于最小长度
*/ */
private function minLength($field, $value): bool private function minLength(string $value): bool
{ {
if (is_array($value)) { return mb_strlen($value) >= $this->value;
if (count($value) < $value) {
return $this->addError($field, 'The param :attribute length error');
}
} else {
if (is_numeric($value) && strlen((string)$value) < $this->value) {
return $this->addError($field, 'The param :attribute length overflow');
}
if (strlen($value) < $this->value) {
return $this->addError($field, 'The param :attribute length error');
}
}
return TRUE;
} }
/** /**
* @param $field * @param string $value
* @param $value
* @return bool * @return bool
* *
* 效验长度是否小于最小长度 * 效验长度是否小于最小长度
*/ */
private function defaultLength($field, $value): bool private function defaultLength(string $value): bool
{ {
if (is_array($value)) { return mb_strlen($value) == $this->value;
if (count($value) !== $value) {
return $this->addError($field, 'The param :attribute length error');
}
} else {
if (is_numeric($value) && strlen((string)$value) !== $this->value) {
return $this->addError($field, 'The param :attribute length overflow');
}
if (mb_strlen($value) !== $this->value) {
return $this->addError($field, 'The param :attribute length error; ' . mb_strlen($value) . ':' . $this->value);
}
}
return TRUE;
} }
} }
+4 -8
View File
@@ -14,18 +14,14 @@ class RequiredValidator extends BaseValidator
{ {
/** /**
* @param string $field
* @param mixed $value
* @return bool * @return bool
* 检查是否存在 * 检查是否存在
*/ */
public function trigger(): bool public function trigger(string $field, mixed $value): bool
{ {
return $this->_validator($this->field, function ($field, $params) { return !is_null($value);
if (!isset($params[$field])) {
return $this->addError($field,'The param :attribute not exists');
} else {
return true;
}
}, $this->params);
} }
} }
+4 -12
View File
@@ -13,23 +13,15 @@ use Exception;
class RoundValidator extends BaseValidator class RoundValidator extends BaseValidator
{ {
public ?int $value = null;
/** /**
* @param string $field
* @param mixed $value
* @return bool * @return bool
* @throws * @throws
*/ */
public function trigger(): bool public function trigger(string $field, mixed $value): bool
{ {
return $this->_validator($this->field, function ($field, $model, $param) { return round($value, $this->value) == $value;
$value = $model->getAttribute($field);
if ($value == null || round($value, $param) != $value) {
return $this->addError($field, 'The param :attribute length error');
}
return true;
}, $this->model, $this->value);
} }
-90
View File
@@ -1,90 +0,0 @@
<?php
namespace validator;
trait RuleTrait
{
/**
* @var array
*/
protected array $classMap = [
'not empty' => [
'class' => EmptyValidator::class,
'method' => EmptyValidator::CAN_NOT_EMPTY,
],
'not null' => [
'class' => EmptyValidator::class,
'method' => EmptyValidator::CAN_NOT_NULL,
],
'required' => [
'class' => RequiredValidator::class,
],
'enum' => [
'class' => EnumValidator::class,
],
'unique' => [
'class' => UniqueValidator::class,
],
'datetime' => [
'class' => DateTimeValidator::class,
'method' => DateTimeValidator::DATE_TIME,
],
'date' => [
'class' => DateTimeValidator::class,
'method' => DateTimeValidator::DATE,
],
'time' => [
'class' => DateTimeValidator::class,
'method' => DateTimeValidator::TIME,
],
'timestamp' => [
'class' => DateTimeValidator::class,
'method' => DateTimeValidator::STR_TO_TIME,
],
'string' => [
'class' => TypesOfValidator::class,
'method' => TypesOfValidator::STRING,
],
'int' => [
'class' => TypesOfValidator::class,
'method' => TypesOfValidator::INTEGER,
],
'min' => [
'class' => IntegerValidator::class
],
'max' => [
'class' => IntegerValidator::class
],
'json' => [
'class' => TypesOfValidator::class,
'method' => TypesOfValidator::JSON,
],
'float' => [
'class' => TypesOfValidator::class,
'method' => TypesOfValidator::FLOAT,
],
'array' => [
'class' => TypesOfValidator::class,
'method' => TypesOfValidator::ARRAY,
],
'maxlength' => [
'class' => LengthValidator::class,
'method' => 'max',
],
'minlength' => [
'class' => LengthValidator::class,
'method' => 'min',
],
'email' => [
'class' => EmailValidator::class,
'method' => 'email',
],
'length' => [
'class' => LengthValidator::class,
'method' => 'default',
],
'round' => [
'class' => RoundValidator::class,
],
];
}
+27 -62
View File
@@ -10,6 +10,9 @@ declare(strict_types=1);
namespace validator; namespace validator;
use Database\ModelInterface;
use function json_validate;
class TypesOfValidator extends BaseValidator class TypesOfValidator extends BaseValidator
{ {
@@ -20,106 +23,68 @@ class TypesOfValidator extends BaseValidator
const string STRING = 'string'; const string STRING = 'string';
const string INTEGER = 'integer'; const string INTEGER = 'integer';
private ?int $min = null;
private ?int $max = null;
/** @var array */
public array $types = [
self::JSON => 'json',
self::FLOAT => 'float',
self::ARRAY => 'array',
self::STRING => 'string',
self::INTEGER => 'integer'
];
/** @var string */ /** @var string */
public string $method; public string $method;
/** /**
* @param string $field
* @param mixed $value
* @return bool * @return bool
*/ */
public function trigger(): bool public function trigger(string $field, mixed $value): bool
{ {
return $this->_validator($this->field, function ($field, $params, $method, $types) { return match ($this->method) {
if (!in_array($method, $types)) { self::INTEGER => $this->integerFormat($value),
return true; self::FLOAT => $this->floatFormat($value),
} self::JSON => $this->jsonFormat($value),
$value = $params[$field] ?? null; self::STRING => $this->stringFormat($value),
return match ($method) { self::ARRAY => $this->arrayFormat($value),
self::INTEGER => $this->integerFormat($field, $value),
self::FLOAT => $this->floatFormat($field, $value),
self::JSON => $this->jsonFormat($field, $value),
self::STRING => $this->stringFormat($field, $value),
self::ARRAY => $this->arrayFormat($field, $value),
}; };
}, $this->params, $this->method, $this->types);
} }
/** /**
* @param $field * @param string|null $value
* @param $value
* @return bool * @return bool
*/ */
public function jsonFormat($field, $value): bool public function jsonFormat(?string $value): bool
{ {
if (!is_string($value) || is_null(json_decode($value))) { return json_validate($value);
return $this->addError($field, 'The ' . $field . ' not is JSON data.');
}
return true;
} }
/** /**
* @param $field * @param mixed $value
* @param $value
* @return bool * @return bool
*/ */
public function arrayFormat($field, $value): bool public function arrayFormat(mixed $value): bool
{ {
if (!is_array($value)) { return is_array($value);
return $this->addError($field, 'The ' . $field . ' not is array data.');
}
return true;
} }
/** /**
* @param $field * @param mixed $value
* @param $value
* @return bool * @return bool
*/ */
public function stringFormat($field, $value): bool public function stringFormat(mixed $value): bool
{ {
if (!is_string($value)) { return is_string($value);
return $this->addError($field, 'The ' . $field . ' not is string data.');
}
return true;
} }
/** /**
* @param $field * @param mixed $value
* @param $value
* @return bool * @return bool
*/ */
public function integerFormat($field, $value): bool public function integerFormat(mixed $value): bool
{ {
if ((int)$value != $value) { return (int)$value == $value;
return $this->addError($field, 'The ' . $field . ' not is number data.');
}
return true;
} }
/** /**
* @param $field * @param mixed $value
* @param $value
* @return bool * @return bool
*/ */
public function floatFormat($field, $value): bool public function floatFormat(mixed $value): bool
{ {
$trim = (float)$value; return (float)$value == $value;
if ($trim != $value) {
return $this->addError($field, 'The ' . $field . ' not is float data.');
}
return true;
} }
} }
+13 -22
View File
@@ -10,37 +10,28 @@ declare(strict_types=1);
namespace validator; namespace validator;
use Database\ModelInterface;
class UniqueValidator extends BaseValidator class UniqueValidator extends BaseValidator
{ {
/** /**
* @var ModelInterface
*/
public ModelInterface $model;
/**
* @param string $field
* @param mixed $value
* @return bool * @return bool
* @throws * @throws
* 检查是否存在 * 检查是否存在
*/ */
public function trigger(): bool public function trigger(string $field, mixed $value): bool
{ {
if (empty($this->model)) { return $this->model::query()->where([$field => $value])->exists() === false;
return $this->addError('model','Model error.');
}
if (!$this->model->getIsNowExample()) {
return true;
}
return $this->_validator($this->field, function ($_item, $params, $model) {
if (!is_array($_item)) {
$_item = [$_item];
}
$data = array_reduce($_item, function ($resp, $next) use ($params) {
$array = empty($resp) ? [] : $resp;
$array[$next] = $params[$next] ?? null;
return $array;
});
if ($model::query()->where($data)->exists()) {
return $this->addError(implode(',', $_item),
'The :attribute \'' . implode(',', $_item) . '\' is exists!');
}
return $this->isFail = TRUE;
}, $this->params, $this->model);
} }
+73 -76
View File
@@ -16,116 +16,113 @@ use Kiri;
class Validator extends BaseValidator class Validator extends BaseValidator
{ {
use RuleTrait; /**
* classMap
*/
const array classMap = [
'not empty' => ['class' => EmptyValidator::class, 'method' => EmptyValidator::CAN_NOT_EMPTY,],
'not null' => ['class' => EmptyValidator::class, 'method' => EmptyValidator::CAN_NOT_NULL,],
'required' => ['class' => RequiredValidator::class,],
'enum' => ['class' => EnumValidator::class,],
'unique' => ['class' => UniqueValidator::class,],
'datetime' => ['class' => DateTimeValidator::class, 'method' => DateTimeValidator::DATE_TIME,],
'date' => ['class' => DateTimeValidator::class, 'method' => DateTimeValidator::DATE,],
'time' => ['class' => DateTimeValidator::class, 'method' => DateTimeValidator::TIME,],
'timestamp' => ['class' => DateTimeValidator::class, 'method' => DateTimeValidator::STR_TO_TIME,],
'string' => ['class' => TypesOfValidator::class, 'method' => TypesOfValidator::STRING,],
'int' => ['class' => TypesOfValidator::class, 'method' => TypesOfValidator::INTEGER,],
'min' => ['class' => IntegerValidator::class],
'max' => ['class' => IntegerValidator::class],
'json' => ['class' => TypesOfValidator::class, 'method' => TypesOfValidator::JSON,],
'float' => ['class' => TypesOfValidator::class, 'method' => TypesOfValidator::FLOAT,],
'array' => ['class' => TypesOfValidator::class, 'method' => TypesOfValidator::ARRAY,],
'maxlength' => ['class' => LengthValidator::class, 'method' => 'max',],
'minlength' => ['class' => LengthValidator::class, 'method' => 'min',],
'email' => ['class' => EmailValidator::class, 'method' => 'email',],
'length' => ['class' => LengthValidator::class, 'method' => 'default',],
'round' => ['class' => RoundValidator::class,],
];
/** @var BaseValidator[] */ /** @var BaseValidator[] */
private ?array $validators = []; private ?array $validators = [];
/** /**
* @param array $params
* @param ModelInterface $model * @param ModelInterface $model
* @return Validator
*/
public static function instance(array $params, ModelInterface $model): static
{
$validator = new Validator();
$validator->setParams($params);
$validator->setModel($model);
return $validator;
}
/**
* @param $field * @param $field
* @param $rules * @param $rules
* @return $this * @return $this
* @throws
*/ */
public function make($field, $rules): static public function make(ModelInterface $model, array $fields, array $rules): static
{ {
if (!is_array($field)) { foreach ($fields as $field) {
$field = [$field]; $this->createRule($field, $rules, $model);
} }
$param = $this->getParams();
$model = $this->getModel();
$this->createRule($field, $rules, $model, $param);
return $this; return $this;
} }
/** /**
* @param $field * @param string $field
* @param $rule * @param array $rule
* @param $model * @param ModelInterface $model
* @param $param * @throws \Exception
* @throws
* ['maxLength'=>150, 'required', 'minLength' => 100]
*/ */
public function createRule($field, $rule, $model, $param): void public function createRule(string $field, array $rule, ModelInterface $model): void
{ {
$define = ['field' => $field]; if (!isset($this->validators[$field])) {
foreach ($rule as $key => $val) { $this->validators[$field] = [];
if (is_string($key)) {
$type = strtolower($key);
$define['value'] = $val;
} else {
$type = strtolower($val);
} }
if (!isset($this->classMap[$type])) { foreach ($rule as $key => $val) {
$this->validators[] = [$model, $val]; if (is_numeric($key) && method_exists($model, $val)) {
$this->validators[$field][] = [$model, $val];
} else { } else {
$merge = array_merge($this->classMap[$type], $define, [ $this->validators[$field][] = $this->mapGen($model, $key, $val);
'params' => $param,
'model' => $model
]);
$this->validators[] = $merge;
} }
} }
} }
/** /**
* @return bool * @param array $defined
* @throws * @param $key
* @param $val
* @return array
* @throws \Exception
*/ */
public function validation(): bool protected function mapGen(ModelInterface $model, $key, $val): array
{
if (is_numeric($key)) {
$defined = self::classMap[$val];
} else {
$defined = self::classMap[$key];
$defined['value'] = $val;
}
if ($defined['class'] == UniqueValidator::class) {
$defined['model'] = $model;
}
return [Kiri::createObject($defined), 'trigger'];
}
/**
* @param ModelInterface $model
* @return bool
*/
public function validation(ModelInterface $model): bool
{ {
if (count($this->validators) < 1) { if (count($this->validators) < 1) {
return true; return true;
} }
foreach ($this->validators as $val) { $attributes = $model->getChanges();
[$result, $validator] = $this->check($val); foreach ($attributes as $field => $attribute) {
if ($result === true) { if (isset($this->validators[$field])) {
continue; $validator = $this->validators[$field];
foreach ($validator as $value) {
if (!call_user_func($value, $field, $attribute)) {
return $this->addError($field, 'field :attribute data format error.');
} }
$isTrue = false;
if ($validator instanceof BaseValidator) {
$this->addError(null, $validator->getError());
} }
break;
} }
$this->validators = [];
return !isset($isTrue);
} }
return true;
/**
* @param BaseValidator|array|Closure $val
* @return array
* @throws
*/
private function check(BaseValidator|array|Closure $val): array
{
if (is_callable($val, true)) {
return [call_user_func($val, $this), $val];
} }
$class = Kiri::getDi()->get($val['class']);
unset($val['class']);
Kiri::configure($class, $val);
return [$class->trigger(), $class];
}
} }