This commit is contained in:
xl
2023-07-07 17:24:03 +08:00
parent 448b1a68fc
commit d18994fde2
11 changed files with 310 additions and 342 deletions
-3
View File
@@ -29,9 +29,6 @@ class ArrayValidator extends BaseValidator
{ {
return $this->_validator($this->field, function ($field, $params) { return $this->_validator($this->field, function ($field, $params) {
$value = $params[$field] ?? null; $value = $params[$field] ?? null;
if (empty($value)) {
return true;
}
if (!is_array($value)) { if (!is_array($value)) {
return $this->addError($field, 'The param :attribute must a array'); return $this->addError($field, 'The param :attribute must a array');
} }
-3
View File
@@ -27,9 +27,6 @@ class DateTimeValidator extends BaseValidator
{ {
return $this->_validator($this->field, function ($field, $params, $method) { return $this->_validator($this->field, function ($field, $params, $method) {
$value = $params[$field] ?? null; $value = $params[$field] ?? null;
if (empty($value)) {
return true;
}
return match ($method) { return match ($method) {
self::DATE => $this->validatorDate($field, $value), self::DATE => $this->validatorDate($field, $value),
self::DATE_TIME => $this->validateDatetime($field, $value), self::DATE_TIME => $this->validateDatetime($field, $value),
+9 -16
View File
@@ -13,26 +13,19 @@ namespace validator;
class EmailValidator extends BaseValidator class EmailValidator extends BaseValidator
{ {
/** /**
* @return bool * @return bool
* 检查是否存在 * 检查是否存在
*/ * @throws \ReflectionException
*/
public function trigger(): bool public function trigger(): bool
{ {
return $this->_validator($this->field, function ($field, $params) { return $this->_validator($this->field, function ($field, $params) {
$value = $params[$field] ?? null; $value = $params[$field] ?? null;
if (empty($value)) { if (!filter_var($value,FILTER_VALIDATE_EMAIL)) {
return true; return $this->addError($field,'The param :attribute format error');
} }
$exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$"; return true;
if (!preg_match($exp, $value)) {
return $this->addError($field,'The param :attribute format error');
}
[$account, $domain] = explode("@", $value);
if (checkdnsrr($domain, "MX")) {
return true;
}
return $this->addError($field,'The param :attribute format error');
}, $this->params); }, $this->params);
} }
+18 -18
View File
@@ -15,13 +15,13 @@ namespace validator;
class EmptyValidator extends BaseValidator class EmptyValidator extends BaseValidator
{ {
/** @var string [不能为空] */ /** @var string [不能为空] */
const CAN_NOT_EMPTY = 'not empty'; const CAN_NOT_EMPTY = 'not empty';
/** @var string [可为空, 不能为null] */ /** @var string [可为空, 不能为null] */
const CAN_NOT_NULL = 'not null'; const CAN_NOT_NULL = 'not null';
public string $method; public string $method;
/** /**
* @return bool * @return bool
@@ -29,17 +29,17 @@ class EmptyValidator extends BaseValidator
* 检查参数是否为NULL * 检查参数是否为NULL
* @throws \ReflectionException * @throws \ReflectionException
*/ */
public function trigger(): bool public function trigger(): bool
{ {
return $this->_validator($this->field, function ($field, $params, $method) { return $this->_validator($this->field, function ($field, $params, $method) {
$value = $params[$field] ?? null; $value = $params[$field] ?? null;
if (empty($value)) { if ($value === null) {
return $this->addError($field,':attribute not exists'); return $this->addError($field, 'The :attribute can not null.');
} }
return match ($method) { if (empty($value)) {
self::CAN_NOT_EMPTY => isset($value[1]) || $this->addError($field,'The :attribute can not empty.'), return $this->addError($field, 'The :attribute can not empty.');
default => $value !== null || $this->addError($field,'The :attribute can not empty.') }
}; return true;
}, $this->params, strtolower($this->method)); }, $this->params, strtolower($this->method));
} }
} }
+13 -18
View File
@@ -12,28 +12,23 @@ namespace validator;
class EnumValidator extends BaseValidator class EnumValidator extends BaseValidator
{ {
public array $value = []; public array $value = [];
/** /**
* @return bool * @return bool
* @throws \ReflectionException * @throws \ReflectionException
*/ */
public function trigger(): bool public function trigger(): bool
{ {
return $this->_validator($this->field, function ($field, $params, $values) { return $this->_validator($this->field, function ($field, $params, $values) {
$value = $params[$field] ?? null; $value = $params[$field] ?? null;
if (is_null($value)) { if (in_array($value, $values)) {
return true; return true;
} }
if ($value === '') { $message = 'The param :attribute value(' . $value . ') only in ' . implode(',', $values);
return $this->addError($field, 'The param :attribute value con\'t empty.'); return $this->addError($field, $message);
}
if (!in_array($value, $values)) { }, $this->params, $this->value);
$message = 'The param :attribute value(' . $value . ') only in ' . implode(',', $values); }
return $this->addError($field, $message);
}
return true;
}, $this->params, $this->value);
}
} }
+4 -6
View File
@@ -19,16 +19,14 @@ class IntegerValidator extends BaseValidator
public ?int $value = null; public ?int $value = null;
private string $type = ''; private string $type = '';
/** /**
* @return bool * @return bool
*/ * @throws \ReflectionException
*/
public function trigger(): bool public function trigger(): bool
{ {
return $this->_validator($this->field, function ($field, $params, $origin, $type) { return $this->_validator($this->field, function ($field, $params, $origin, $type) {
$value = $params[$field] ?? null; $value = $params[$field] ?? null;
if (empty($value)) {
return true;
}
if ($type !== self::MIN && $value < $origin) { if ($type !== self::MIN && $value < $origin) {
return $this->addError($field,'The ' . $field . ' cannot be less than the default value.'); return $this->addError($field,'The ' . $field . ' cannot be less than the default value.');
} }
+30 -31
View File
@@ -10,6 +10,8 @@ declare(strict_types=1);
namespace validator; namespace validator;
use ReflectionException;
class LengthValidator extends BaseValidator class LengthValidator extends BaseValidator
{ {
@@ -20,20 +22,14 @@ class LengthValidator extends BaseValidator
public int $value; public int $value;
/** /**
* @return bool * @return bool
*/ * @throws ReflectionException
*/
public function trigger(): bool public function trigger(): bool
{ {
return $this->_validator($this->field, function ($field, $params, $method, $length) { return $this->_validator($this->field, function ($field, $params, $method, $length) {
$value = $params[$field] ?? null; $value = $params[$field] ?? null;
if (empty($value)) {
if ($method != self::MAX_LENGTH) {
return $this->addError($field, 'The param :attribute not exists');
} else {
return TRUE;
}
}
return match ($method) { return match ($method) {
self::MAX_LENGTH => $this->maxLength($field, (string)$value), self::MAX_LENGTH => $this->maxLength($field, (string)$value),
self::MIN_LENGTH => $this->minLength($field, (string)$value), self::MIN_LENGTH => $this->minLength($field, (string)$value),
@@ -42,13 +38,14 @@ class LengthValidator extends BaseValidator
}, $this->params, strtolower($this->method), $this->value); }, $this->params, strtolower($this->method), $this->value);
} }
/** /**
* @param $field * @param $field
* @param $value * @param $value
* @return bool * @return bool
* *
* 效验长度是否大于最大长度 * 效验长度是否大于最大长度
*/ * @throws ReflectionException
*/
private function maxLength($field, $value): bool private function maxLength($field, $value): bool
{ {
if (is_array($value)) { if (is_array($value)) {
@@ -66,13 +63,14 @@ class LengthValidator extends BaseValidator
return TRUE; return TRUE;
} }
/** /**
* @param $field * @param $field
* @param $value * @param $value
* @return bool * @return bool
* *
* 效验长度是否小于最小长度 * 效验长度是否小于最小长度
*/ * @throws ReflectionException
*/
private function minLength($field, $value): bool private function minLength($field, $value): bool
{ {
if (is_array($value)) { if (is_array($value)) {
@@ -90,13 +88,14 @@ class LengthValidator extends BaseValidator
return TRUE; return TRUE;
} }
/** /**
* @param $field * @param $field
* @param $value * @param $value
* @return bool * @return bool
* *
* 效验长度是否小于最小长度 * 效验长度是否小于最小长度
*/ * @throws ReflectionException
*/
private function defaultLength($field, $value): bool private function defaultLength($field, $value): bool
{ {
if (is_array($value)) { if (is_array($value)) {
+5 -4
View File
@@ -13,10 +13,11 @@ namespace validator;
class RequiredValidator extends BaseValidator class RequiredValidator extends BaseValidator
{ {
/** /**
* @return bool * @return bool
* 检查是否存在 * 检查是否存在
*/ * @throws \ReflectionException
*/
public function trigger(): bool public function trigger(): bool
{ {
return $this->_validator($this->field, function ($field, $params) { return $this->_validator($this->field, function ($field, $params) {
+94
View File
@@ -0,0 +1,94 @@
<?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,
],
'serialize' => [
'class' => TypesOfValidator::class,
'method' => TypesOfValidator::SERIALIZE,
],
'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,
],
];
}
+39 -45
View File
@@ -48,50 +48,45 @@ class TypesOfValidator extends BaseValidator
return true; return true;
} }
$value = $params[$field] ?? null; $value = $params[$field] ?? null;
if (is_null($value)) {
return true;
}
return $this->{$method . 'Format'}($field, $value); return $this->{$method . 'Format'}($field, $value);
}, $this->params, $this->method, $this->types); }, $this->params, $this->method, $this->types);
} }
/** /**
* @param $field * @param $field
* @param $value * @param $value
* @return bool * @return bool
*/ * @throws \ReflectionException
*/
public function jsonFormat($field, $value): bool public function jsonFormat($field, $value): bool
{ {
if (!is_string($value) || is_numeric($value)) {
return $this->addError($field, 'The ' . $field . ' not is JSON data.');
}
if (is_null(json_decode($value))) { if (is_null(json_decode($value))) {
return $this->addError($field, 'The ' . $field . ' not is JSON data.'); return $this->addError($field, 'The ' . $field . ' not is JSON data.');
} }
return true; return true;
} }
/** /**
* @param $field * @param $field
* @param $value * @param $value
* @return bool * @return bool
*/ * @throws \ReflectionException
*/
public function serializeFormat($field, $value): bool public function serializeFormat($field, $value): bool
{ {
if (!is_string($value) || is_numeric($value)) { if (false === unserialize($value)) {
return $this->addError($field, 'The ' . $field . ' not is serialize data.');
}
if (false === swoole_unserialize($value)) {
return $this->addError($field, 'The ' . $field . ' not is serialize data.'); return $this->addError($field, 'The ' . $field . ' not is serialize data.');
} }
return true; return true;
} }
/** /**
* @param $field * @param $field
* @param $value * @param $value
* @return bool * @return bool
*/ * @throws \ReflectionException
*/
public function arrayFormat($field, $value): bool public function arrayFormat($field, $value): bool
{ {
if (!is_array($value)) { if (!is_array($value)) {
@@ -100,41 +95,40 @@ class TypesOfValidator extends BaseValidator
return true; return true;
} }
/** /**
* @param $field * @param $field
* @param $value * @param $value
* @return bool * @return bool
*/ * @throws \ReflectionException
*/
public function stringFormat($field, $value): bool public function stringFormat($field, $value): bool
{ {
if (is_array($value) || is_object($value) || is_bool($value)) { if (!is_string($value)) {
return $this->addError($field, 'The ' . $field . ' not is string data.'); return $this->addError($field, 'The ' . $field . ' not is string data.');
} }
return true; return true;
} }
/** /**
* @param $field * @param $field
* @param $value * @param $value
* @return bool * @return bool
*/ * @throws \ReflectionException
*/
public function integerFormat($field, $value): bool public function integerFormat($field, $value): bool
{ {
if (!is_numeric($value)) {
return $this->addError($field, 'The ' . $field . ' not is number data.');
}
if ((int)$value != $value) { if ((int)$value != $value) {
return $this->addError($field, 'The ' . $field . ' not is number data.'); return $this->addError($field, 'The ' . $field . ' not is number data.');
} }
return true; return true;
} }
/** /**
* @param $field * @param $field
* @param $value * @param $value
* @return bool * @return bool
*/ * @throws \ReflectionException
*/
public function floatFormat($field, $value): bool public function floatFormat($field, $value): bool
{ {
$trim = (float)$value; $trim = (float)$value;
+98 -198
View File
@@ -17,216 +17,116 @@ use Kiri;
class Validator extends BaseValidator class Validator extends BaseValidator
{ {
/** @var BaseValidator[] */ use RuleTrait;
private ?array $validators = [];
/** @var ?Validator */ /** @var BaseValidator[] */
private static ?Validator $instance = null; private ?array $validators = [];
protected array $classMap = [
'not empty' => [
'class' => 'validator\EmptyValidator',
'method' => EmptyValidator::CAN_NOT_EMPTY,
],
'not null' => [
'class' => 'validator\EmptyValidator',
'method' => EmptyValidator::CAN_NOT_NULL,
],
'required' => [
'class' => 'validator\RequiredValidator',
],
'enum' => [
'class' => 'validator\EnumValidator',
],
'unique' => [
'class' => 'validator\UniqueValidator',
],
'datetime' => [
'class' => 'validator\DatetimeValidator',
'method' => DateTimeValidator::DATE_TIME,
],
'date' => [
'class' => 'validator\DatetimeValidator',
'method' => DateTimeValidator::DATE,
],
'time' => [
'class' => 'validator\DatetimeValidator',
'method' => DateTimeValidator::TIME,
],
'timestamp' => [
'class' => 'validator\DatetimeValidator',
'method' => DateTimeValidator::STR_TO_TIME,
],
'string' => [
'class' => 'validator\TypesOfValidator',
'method' => TypesOfValidator::STRING,
],
'int' => [
'class' => 'validator\TypesOfValidator',
'method' => TypesOfValidator::INTEGER,
],
'min' => [
'class' => IntegerValidator::class
],
'max' => [
'class' => IntegerValidator::class
],
'json' => [
'class' => 'validator\TypesOfValidator',
'method' => TypesOfValidator::JSON,
],
'float' => [
'class' => 'validator\TypesOfValidator',
'method' => TypesOfValidator::FLOAT,
],
'array' => [
'class' => 'validator\TypesOfValidator',
'method' => TypesOfValidator::ARRAY,
],
'serialize' => [
'class' => 'validator\TypesOfValidator',
'method' => TypesOfValidator::SERIALIZE,
],
'maxlength' => [
'class' => 'validator\LengthValidator',
'method' => 'max',
],
'minlength' => [
'class' => 'validator\LengthValidator',
'method' => 'min',
],
'email' => [
'class' => 'validator\EmailValidator',
'method' => 'email',
],
'length' => [
'class' => 'validator\LengthValidator',
'method' => 'default',
],
'round' => [
'class' => 'validator\RoundValidator',
],
];
/**
* @return Validator|null
*/
public static function getInstance(): ?Validator
{
if (static::$instance == null) {
static::$instance = new Validator();
}
return static::$instance;
}
/** /**
* @param array $params * @param array $params
* @param ModelInterface $model * @param ModelInterface $model
* @return Validator * @return Validator
*/ */
public static function instance(array $params, ModelInterface $model): static public static function instance(array $params, ModelInterface $model): static
{ {
$validator = static::$instance; $validator = new Validator();
if ($validator == null) { $validator->setParams($params);
$validator = static::$instance = new Validator(); $validator->setModel($model);
} return $validator;
$validator->setParams($params); }
$validator->setModel($model);
return $validator;
}
/** /**
* @param $field * @param $field
* @param $rules * @param $rules
* @return $this * @return $this
* @throws Exception * @throws Exception
*/ */
public function make($field, $rules): static public function make($field, $rules): static
{ {
if (!is_array($field)) { if (!is_array($field)) {
$field = [$field]; $field = [$field];
} }
$param = $this->getParams(); $param = $this->getParams();
$model = $this->getModel(); $model = $this->getModel();
$this->createRule($field, $rules, $model, $param); $this->createRule($field, $rules, $model, $param);
return $this; return $this;
} }
/** /**
* @param $field * @param $field
* @param $rule * @param $rule
* @param $model * @param $model
* @param $param * @param $param
* @throws Exception * @throws Exception
* ['maxLength'=>150, 'required', 'minLength' => 100] * ['maxLength'=>150, 'required', 'minLength' => 100]
*/ */
public function createRule($field, $rule, $model, $param): void public function createRule($field, $rule, $model, $param): void
{ {
$define = ['field' => $field]; $define = ['field' => $field];
foreach ($rule as $key => $val) { foreach ($rule as $key => $val) {
if (is_string($key)) { if (is_string($key)) {
$type = strtolower($key); $type = strtolower($key);
$define['value'] = $val; $define['value'] = $val;
} else { } else {
$type = strtolower($val); $type = strtolower($val);
} }
if (!isset($this->classMap[$type])) { if (!isset($this->classMap[$type])) {
$this->validators[] = [$model, $val]; $this->validators[] = [$model, $val];
} else { } else {
$merge = array_merge($this->classMap[$type], $define, [ $merge = array_merge($this->classMap[$type], $define, [
'params' => $param, 'params' => $param,
'model' => $model 'model' => $model
]); ]);
$this->validators[] = $merge; $this->validators[] = $merge;
} }
} }
} }
/** /**
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function validation(): bool public function validation(): bool
{ {
if (count($this->validators) < 1) { if (count($this->validators) < 1) {
return true; return true;
} }
foreach ($this->validators as $val) { foreach ($this->validators as $val) {
[$result, $validator] = $this->check($val); [$result, $validator] = $this->check($val);
if ($result === true) { if ($result === true) {
continue; continue;
} }
$isTrue = false; $isTrue = false;
if ($validator instanceof BaseValidator) { if ($validator instanceof BaseValidator) {
$this->addError(null, $validator->getError()); $this->addError(null, $validator->getError());
} }
break; break;
} }
$this->validators = []; $this->validators = [];
return !isset($isTrue); return !isset($isTrue);
} }
/** /**
* @param BaseValidator|array|Closure $val * @param BaseValidator|array|Closure $val
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
private function check(BaseValidator|array|Closure $val): mixed private function check(BaseValidator|array|Closure $val): mixed
{ {
if (is_callable($val, true)) { if (is_callable($val, true)) {
return [call_user_func($val, $this), $val]; return [call_user_func($val, $this), $val];
} }
$class = Kiri::getDi()->get($val['class']); $class = Kiri::getDi()->get($val['class']);
unset($val['class']); unset($val['class']);
Kiri::configure($class, $val); Kiri::configure($class, $val);
return [$class->trigger(), $class]; return [$class->trigger(), $class];
} }
} }