From 645d73453cd9154a44adb3bc1f4bd3d43845a6a8 Mon Sep 17 00:00:00 2001 From: whwyy Date: Mon, 18 Dec 2023 15:01:09 +0800 Subject: [PATCH] eee --- ArrayValidator.php | 68 +++++++++---------- BaseValidator.php | 119 +++----------------------------- DateTimeValidator.php | 78 ++++++--------------- EmailValidator.php | 16 ++--- EmptyValidator.php | 19 +++--- EnumValidator.php | 16 ++--- IntegerValidator.php | 27 +++----- LengthValidator.php | 98 ++++++++------------------- RequiredValidator.php | 16 ++--- RoundValidator.php | 16 ++--- RuleTrait.php | 90 ------------------------- TypesOfValidator.php | 97 +++++++++----------------- UniqueValidator.php | 49 ++++++-------- Validator.php | 153 +++++++++++++++++++++--------------------- composer.json | 2 +- 15 files changed, 251 insertions(+), 613 deletions(-) delete mode 100644 RuleTrait.php diff --git a/ArrayValidator.php b/ArrayValidator.php index e741b9a..e62b72d 100644 --- a/ArrayValidator.php +++ b/ArrayValidator.php @@ -1,36 +1,32 @@ -_validator($this->field, function ($field, $params) { - $value = $params[$field] ?? null; - if (!is_array($value)) { - return $this->addError($field, 'The param :attribute must a array'); - } - return true; - }, $this->params); - } - -} +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; - } - } - - /** + * @param string $field + * @param float $value * @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'); } - /** - * @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 @@ -103,36 +40,13 @@ abstract class BaseValidator */ public function addError($field, $message): bool { - $this->isFail = FALSE; - if (!is_null($field)) { $message = str_replace(':attribute', $field, $message); } - \trigger_print_error($message, "mysql"); $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 true; + return false; } @@ -143,21 +57,4 @@ abstract class BaseValidator { 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); - } - } } diff --git a/DateTimeValidator.php b/DateTimeValidator.php index 412e4ee..1b65186 100644 --- a/DateTimeValidator.php +++ b/DateTimeValidator.php @@ -21,104 +21,64 @@ class DateTimeValidator extends BaseValidator public string $method; /** + * @param string $field + * @param mixed $value * @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; - return match ($method) { - self::DATE => $this->validatorDate($field, $value), - self::DATE_TIME => $this->validateDatetime($field, $value), - self::TIME => $this->validatorTime($field, $value), - self::STR_TO_TIME => $this->validatorTimestamp($field, $value), - default => true, - }; - }, $this->params, strtolower($this->method)); - - + $value = $params[$field] ?? null; + return match ($this->method) { + self::DATE => $this->validatorDate($value), + self::DATE_TIME => $this->validateDatetime($value), + self::TIME => $this->validatorTime($value), + self::STR_TO_TIME => $this->validatorTimestamp($value), + default => true, + }; } /** - * @param $field * @param $value * @return bool * * 效验分秒 格式如 01:02 or 01-02 */ - public function validatorTime($field, $value): bool + public function validatorTime($value): bool { - if (!is_string($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'); - } + return (bool)preg_match('/^\d{2}:\d{2}(:\d{2})?+(\.\d+)?$/', $value); } /** - * @param $field * @param $value * @return bool * * 效验分秒 格式如 2017-12-22 01:02 */ - public function validateDatetime($field, $value): bool + public function validateDatetime($value): bool { - if (!is_string($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'); - } + return (bool)preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?+(\.\d+)?$/', $value); } /** - * @param $field * @param $value * @return bool * * 效验分秒 格式如 2017-12-22 */ - public function validatorDate($field, $value): bool + public function validatorDate($value): bool { - if (!is_string($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'); - } + return (bool)preg_match('/^\d{4}-\d{2}-\d{2}$/', $value); } /** - * @param $field * @param $value * @return bool * * 效验时间戳 格式如 1521452254 */ - public function validatorTimestamp($field, $value): bool + public function validatorTimestamp($value): bool { - if (!is_numeric($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; + return (bool)preg_match('/^1\d{9}$/', $value); } } diff --git a/EmailValidator.php b/EmailValidator.php index bd4d732..d2e69d9 100644 --- a/EmailValidator.php +++ b/EmailValidator.php @@ -16,18 +16,14 @@ class EmailValidator extends BaseValidator { /** + * @param string $field + * @param mixed $value * @return bool * 检查是否存在 */ - public function trigger(): bool - { - return $this->_validator($this->field, function ($field, $params) { - $value = $params[$field] ?? null; - if (!filter_var($value,FILTER_VALIDATE_EMAIL)) { - return $this->addError($field,'The param :attribute format error'); - } - return true; - }, $this->params); - } + public function trigger(string $field, mixed $value): bool + { + return filter_var($value, FILTER_VALIDATE_EMAIL); + } } diff --git a/EmptyValidator.php b/EmptyValidator.php index 73eeb13..0c0a90f 100644 --- a/EmptyValidator.php +++ b/EmptyValidator.php @@ -27,21 +27,18 @@ class EmptyValidator extends BaseValidator public string $method; /** + * @param string $field + * @param mixed $value * @return bool * * 检查参数是否为NULL */ - 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; - if ($value === null) { - return $this->addError($field, 'The :attribute can not null.'); - } - if (empty($value)) { - return $this->addError($field, 'The :attribute can not empty.'); - } - return true; - }, $this->params, strtolower($this->method)); + return match ($this->method) { + self::CAN_NOT_NULL => !is_null($value), + self::CAN_NOT_EMPTY => !empty($value), + default => true + }; } } diff --git a/EnumValidator.php b/EnumValidator.php index fa2627a..245eae0 100644 --- a/EnumValidator.php +++ b/EnumValidator.php @@ -12,22 +12,14 @@ namespace validator; class EnumValidator extends BaseValidator { - public array $value = []; - /** + * @param string $field + * @param mixed $value * @return bool */ - public function trigger(): bool + public function trigger(string $field, mixed $value): bool { - return $this->_validator($this->field, function ($field, $params, $values) { - $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); + return in_array($value, $this->value); } } diff --git a/IntegerValidator.php b/IntegerValidator.php index f8798b1..952d7b8 100644 --- a/IntegerValidator.php +++ b/IntegerValidator.php @@ -10,32 +10,21 @@ declare(strict_types=1); namespace validator; +use Database\ModelInterface; + /** * */ 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 */ - public function trigger(): bool - { - return $this->_validator($this->field, function ($field, $params, $origin, $type) { - $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); - } + public function trigger(string $field, mixed $value): bool + { + return (float)$value == $value; + } } diff --git a/LengthValidator.php b/LengthValidator.php index 8c5ee31..c9db265 100644 --- a/LengthValidator.php +++ b/LengthValidator.php @@ -13,97 +13,57 @@ namespace validator; class LengthValidator extends BaseValidator { - const string MAX_LENGTH = 'max'; - const string MIN_LENGTH = 'min'; + const string MAX_LENGTH = 'max'; + const string MIN_LENGTH = 'min'; - public string $method; + public string $method; - public int $value; + public int $value; /** + * @param string $field + * @param mixed $value * @return bool */ - public function trigger(): bool - { - return $this->_validator($this->field, function ($field, $params, $method, $length) { - $value = $params[$field] ?? null; - return match ($method) { - self::MAX_LENGTH => $this->maxLength($field, (string)$value), - self::MIN_LENGTH => $this->minLength($field, (string)$value), - default => $this->defaultLength($field, (string)$value), - }; - }, $this->params, strtolower($this->method), $this->value); - } + public function trigger(string $field, mixed $value): bool + { + return match ($this->method) { + self::MAX_LENGTH => $this->maxLength((string)$value), + self::MIN_LENGTH => $this->minLength((string)$value), + default => $this->defaultLength((string)$value), + }; + } /** - * @param $field - * @param $value + * @param string $value * @return bool * * 效验长度是否大于最大长度 */ - private function maxLength($field, $value): bool - { - if (is_array($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; - } + private function maxLength(string $value): bool + { + return mb_strlen($value) <= $this->value; + } /** - * @param $field - * @param $value + * @param string $value * @return bool * * 效验长度是否小于最小长度 */ - private function minLength($field, $value): bool - { - if (is_array($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; - } + private function minLength(string $value): bool + { + return mb_strlen($value) >= $this->value; + } /** - * @param $field - * @param $value + * @param string $value * @return bool * * 效验长度是否小于最小长度 */ - private function defaultLength($field, $value): bool - { - if (is_array($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; - } + private function defaultLength(string $value): bool + { + return mb_strlen($value) == $this->value; + } } diff --git a/RequiredValidator.php b/RequiredValidator.php index 244e9a4..f076322 100644 --- a/RequiredValidator.php +++ b/RequiredValidator.php @@ -14,18 +14,14 @@ class RequiredValidator extends BaseValidator { /** + * @param string $field + * @param mixed $value * @return bool * 检查是否存在 */ - public function trigger(): bool - { - return $this->_validator($this->field, function ($field, $params) { - if (!isset($params[$field])) { - return $this->addError($field,'The param :attribute not exists'); - } else { - return true; - } - }, $this->params); - } + public function trigger(string $field, mixed $value): bool + { + return !is_null($value); + } } diff --git a/RoundValidator.php b/RoundValidator.php index 4c39641..2462624 100644 --- a/RoundValidator.php +++ b/RoundValidator.php @@ -13,23 +13,15 @@ use Exception; class RoundValidator extends BaseValidator { - - public ?int $value = null; - - /** + * @param string $field + * @param mixed $value * @return bool * @throws */ - public function trigger(): bool + public function trigger(string $field, mixed $value): bool { - return $this->_validator($this->field, function ($field, $model, $param) { - $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); + return round($value, $this->value) == $value; } diff --git a/RuleTrait.php b/RuleTrait.php deleted file mode 100644 index 5315b02..0000000 --- a/RuleTrait.php +++ /dev/null @@ -1,90 +0,0 @@ - [ - '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, - ], - ]; -} \ No newline at end of file diff --git a/TypesOfValidator.php b/TypesOfValidator.php index c852d07..ec268df 100644 --- a/TypesOfValidator.php +++ b/TypesOfValidator.php @@ -10,116 +10,81 @@ declare(strict_types=1); namespace validator; +use Database\ModelInterface; +use function json_validate; + class TypesOfValidator extends BaseValidator { - const string JSON = 'json'; - const string FLOAT = 'float'; - const string ARRAY = 'array'; + const string JSON = 'json'; + const string FLOAT = 'float'; + const string ARRAY = 'array'; const string STRING = 'string'; 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 */ public string $method; - /** + * @param string $field + * @param mixed $value * @return bool */ - public function trigger(): bool + public function trigger(string $field, mixed $value): bool { - return $this->_validator($this->field, function ($field, $params, $method, $types) { - if (!in_array($method, $types)) { - return true; - } - $value = $params[$field] ?? null; - return match ($method) { - 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); + return match ($this->method) { + self::INTEGER => $this->integerFormat($value), + self::FLOAT => $this->floatFormat($value), + self::JSON => $this->jsonFormat($value), + self::STRING => $this->stringFormat($value), + self::ARRAY => $this->arrayFormat($value), + }; } /** - * @param $field - * @param $value + * @param string|null $value * @return bool */ - public function jsonFormat($field, $value): bool + public function jsonFormat(?string $value): bool { - if (!is_string($value) || is_null(json_decode($value))) { - return $this->addError($field, 'The ' . $field . ' not is JSON data.'); - } - return true; + return json_validate($value); } /** - * @param $field - * @param $value + * @param mixed $value * @return bool */ - public function arrayFormat($field, $value): bool + public function arrayFormat(mixed $value): bool { - if (!is_array($value)) { - return $this->addError($field, 'The ' . $field . ' not is array data.'); - } - return true; + return is_array($value); } /** - * @param $field - * @param $value + * @param mixed $value * @return bool */ - public function stringFormat($field, $value): bool + public function stringFormat(mixed $value): bool { - if (!is_string($value)) { - return $this->addError($field, 'The ' . $field . ' not is string data.'); - } - return true; + return is_string($value); } /** - * @param $field - * @param $value + * @param mixed $value * @return bool */ - public function integerFormat($field, $value): bool + public function integerFormat(mixed $value): bool { - if ((int)$value != $value) { - return $this->addError($field, 'The ' . $field . ' not is number data.'); - } - return true; + return (int)$value == $value; } /** - * @param $field - * @param $value + * @param mixed $value * @return bool */ - public function floatFormat($field, $value): bool + public function floatFormat(mixed $value): bool { - $trim = (float)$value; - if ($trim != $value) { - return $this->addError($field, 'The ' . $field . ' not is float data.'); - } - return true; + return (float)$value == $value; } } diff --git a/UniqueValidator.php b/UniqueValidator.php index 41a1814..2fecbbe 100644 --- a/UniqueValidator.php +++ b/UniqueValidator.php @@ -10,38 +10,29 @@ declare(strict_types=1); namespace validator; +use Database\ModelInterface; + class UniqueValidator extends BaseValidator { - /** - * @return bool - * @throws - * 检查是否存在 - */ - public function trigger(): bool - { - if (empty($this->model)) { - 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); - } + + /** + * @var ModelInterface + */ + public ModelInterface $model; + + + /** + * @param string $field + * @param mixed $value + * @return bool + * @throws + * 检查是否存在 + */ + public function trigger(string $field, mixed $value): bool + { + return $this->model::query()->where([$field => $value])->exists() === false; + } } diff --git a/Validator.php b/Validator.php index 0878400..d6fe049 100644 --- a/Validator.php +++ b/Validator.php @@ -16,116 +16,113 @@ use Kiri; 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[] */ private ?array $validators = []; /** - * @param array $params * @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 $rules * @return $this - * @throws */ - public function make($field, $rules): static + public function make(ModelInterface $model, array $fields, array $rules): static { - if (!is_array($field)) { - $field = [$field]; + foreach ($fields as $field) { + $this->createRule($field, $rules, $model); } - - $param = $this->getParams(); - $model = $this->getModel(); - - $this->createRule($field, $rules, $model, $param); - return $this; } /** - * @param $field - * @param $rule - * @param $model - * @param $param - * @throws - * ['maxLength'=>150, 'required', 'minLength' => 100] + * @param string $field + * @param array $rule + * @param ModelInterface $model + * @throws \Exception */ - 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])) { + $this->validators[$field] = []; + } foreach ($rule as $key => $val) { - if (is_string($key)) { - $type = strtolower($key); - $define['value'] = $val; + if (is_numeric($key) && method_exists($model, $val)) { + $this->validators[$field][] = [$model, $val]; } else { - $type = strtolower($val); - } - if (!isset($this->classMap[$type])) { - $this->validators[] = [$model, $val]; - } else { - $merge = array_merge($this->classMap[$type], $define, [ - 'params' => $param, - 'model' => $model - ]); - $this->validators[] = $merge; + $this->validators[$field][] = $this->mapGen($model, $key, $val); } } } + /** - * @return bool - * @throws + * @param array $defined + * @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) { return true; } - foreach ($this->validators as $val) { - [$result, $validator] = $this->check($val); - if ($result === true) { - continue; + $attributes = $model->getChanges(); + foreach ($attributes as $field => $attribute) { + if (isset($this->validators[$field])) { + $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]; - } - } diff --git a/composer.json b/composer.json index 66d9096..a0d8df5 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ "autoload": { "psr-4": { "validator\\": "./" - } + } }, "require-dev": { }