44 Commits

Author SHA1 Message Date
as2252258 2c554e765c eee 2024-01-10 17:35:55 +08:00
as2252258 21aca8b642 eee 2023-12-19 14:51:13 +08:00
as2252258 6621c5f247 eee 2023-12-18 18:24:39 +08:00
as2252258 271e481035 eee 2023-12-18 17:22:29 +08:00
as2252258 8684ab7045 eee 2023-12-18 15:20:58 +08:00
as2252258 49cefbd1f9 eee 2023-12-18 15:04:56 +08:00
as2252258 55a656bb6f eee 2023-12-18 15:04:17 +08:00
as2252258 320bfb9b64 eee 2023-12-18 15:02:12 +08:00
as2252258 645d73453c eee 2023-12-18 15:01:09 +08:00
as2252258 d860269a7c eee 2023-12-12 15:35:34 +08:00
as2252258 26030fd148 eee 2023-10-24 17:22:29 +08:00
as2252258 f194684d4b eee 2023-10-08 17:55:11 +08:00
as2252258 8f680d5368 eee 2023-09-30 12:07:36 +08:00
as2252258 0547948b3b eee 2023-09-12 20:52:18 +08:00
as2252258 80f9bfc443 qqq 2023-08-21 16:31:58 +08:00
as2252258 7579bf8fbe qqq 2023-07-31 23:08:59 +08:00
as2252258 77c2d18bd7 qqq 2023-07-26 09:58:34 +08:00
as2252258 d18994fde2 qqq 2023-07-07 17:24:03 +08:00
as2252258 448b1a68fc qqq 2023-05-09 10:17:10 +08:00
as2252258 30b99ad98a qqq 2023-05-09 10:11:21 +08:00
as2252258 b2a3c30e24 e 2023-05-06 17:20:51 +08:00
as2252258 f368ff97ab 变更 2023-04-25 17:05:06 +08:00
as2252258 726742f66f 变更 2023-04-21 23:09:35 +08:00
as2252258 232d0535f5 变更 2023-04-20 14:48:50 +08:00
as2252258 5fdc507b71 变更 2023-04-20 14:44:17 +08:00
as2252258 a61b0618e0 变更 2023-04-10 17:13:24 +08:00
as2252258 5f110403aa 变更 2022-09-18 03:44:51 +08:00
as2252258 c8194f3089 变更 2022-09-17 19:28:53 +08:00
as2252258 60cd694671 modify plugin name 2022-03-01 18:14:03 +08:00
as2252258 83e4c8a5ba modify plugin name 2022-03-01 16:43:50 +08:00
as2252258 e2bdf81267 modify plugin name 2022-03-01 16:38:22 +08:00
as2252258 74eac11f6c modify plugin name 2022-03-01 16:36:31 +08:00
as2252258 a87b6288be modify plugin name 2022-03-01 16:33:02 +08:00
as2252258 0ef74f1096 modify plugin name 2022-03-01 16:32:32 +08:00
as2252258 ad4e1743b4 modify plugin name 2022-03-01 16:18:49 +08:00
as2252258 e6dc3bf70f modify plugin name 2022-02-27 15:29:23 +08:00
as2252258 ff58f2392a modify plugin name 2022-02-25 17:17:29 +08:00
as2252258 db725b710d modify plugin name 2022-02-25 17:12:15 +08:00
as2252258 14dd7efda6 modify plugin name 2022-02-18 18:55:05 +08:00
as2252258 ba410c90da modify plugin name 2022-02-18 17:16:45 +08:00
as2252258 1acf3fb48b modify plugin name 2022-02-10 16:36:58 +08:00
as2252258 485b39390e Revert "改名"
This reverts commit fdf58326
2022-01-12 14:10:32 +08:00
as2252258 9fa7d2828c e 2022-01-09 14:01:11 +08:00
as2252258 2288ea4778 1 2022-01-09 02:44:06 +08:00
15 changed files with 671 additions and 1081 deletions
+34 -34
View File
@@ -1,34 +1,34 @@
# Created by .ignore support plugin (hsz.mobi) # Created by .ignore support plugin (hsz.mobi)
### Yii template ### Yii template
assets/* assets/*
!assets/.gitignore !assets/.gitignore
protected/runtime/* protected/runtime/*
!protected/runtime/.gitignore !protected/runtime/.gitignore
protected/data/*.db protected/data/*.db
themes/classic/views/ themes/classic/views/
### Example user template template ### Example user template template
### Example user template ### Example user template
# IntelliJ project files # IntelliJ project files
.idea .idea
*.iml *.iml
out out
gen gen
composer.lock composer.lock
*.log *.log
commands/result commands/result
config/setting.php config/setting.php
tests/ tests/
vendor/ vendor/
runtime/ runtime/
*.xml *.xml
*.lock *.lock
oot oot
d d
composer.lock composer.lock
+10 -48
View File
@@ -17,53 +17,15 @@ namespace validator;
class ArrayValidator extends BaseValidator class ArrayValidator extends BaseValidator
{ {
/** /**
* @return bool * @param mixed $value
* * @return bool
* 检查 *
*/ * 检查
public function trigger(): bool */
{ public function trigger(mixed $value): bool
if (empty($this->params)) { {
return true; return is_array($value);
} }
if (!isset($this->params[$this->field])) {
return true;
}
if (!is_array($this->params[$this->field])) {
return $this->addError("The param :attribute must a array");
}
return true;
}
/**
* @param $data
* @return array
*
* 转成数组
*/
private function toArray($data): array
{
if (is_numeric($data)) {
return [];
} else if (is_null(json_decode($data, true))) {
return [];
} elseif (is_object($data)) {
$data = get_object_vars($data);
}
$_tmp = [];
foreach ($data as $key => $val) {
if (is_object($val)) {
$_tmp[$key] = $this->toArray($val);
} else if (is_array($val)) {
$_tmp[$key] = $this->toArray($val);
} else {
$_tmp[$key] = $val;
}
}
return $_tmp;
}
} }
+52 -137
View File
@@ -1,137 +1,52 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
use Database\Model; use Exception;
use Exception;
abstract class BaseValidator /**
{ * Class \validator\BaseValidator
*/
public string $field = ''; abstract class BaseValidator
{
public array $rules = [];
public mixed $value;
public string $method;
protected bool $isFail = TRUE; protected string $message;
protected string $message = '';
/**
protected array $params = []; * @param float $value
* @return bool
protected ?Model $model = null; * @throws Exception
*/
public function trigger(mixed $value): bool
/** {
* @param $model throw new Exception('Child Class must define method of trigger');
*/ }
public function setModel($model)
{
$this->model = $model; /**
} * @param string $field
* @param string $message
/** * @return bool
* @return Model|null */
*/ public function addError(string $field, string $message): bool
public function getModel(): ?Model {
{ $this->message = str_replace(':attribute', $field, $message);
return $this->model; return false;
} }
/** /**
* BaseValidator constructor. * @return string
* @param array $config */
*/ public function getError(): string
public function __construct(array $config = []) {
{ return $this->message;
$this->regConfig($config); }
} }
/**
* @param $config
*/
private function regConfig($config)
{
if (empty($config) || !is_array($config)) {
return;
}
foreach ($config as $key => $val) {
$this->$key = $val;
}
}
/**
* @return bool
* @throws Exception
*/
public function trigger(): bool
{
throw new Exception('Child Class must define method of trigger');
}
/**
* @return array
*/
protected function getParams(): array
{
return $this->params;
}
/**
* @param array|null $data
* @return $this
*/
public function setParams(?array $data): static
{
if (is_null($data)) {
$data = [];
}
$this->params = $data;
return $this;
}
/**
* @param $message
* @return bool
*/
public function addError($message): bool
{
$this->isFail = FALSE;
$message = str_replace(':attribute', $this->field, $message);
$this->message = $message;
return $this->isFail;
}
/**
* @return string
*/
public function getError(): string
{
return $this->message;
}
/**
* @param $name
* @param $value
* @throws Exception
*/
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);
}
}
}
+82 -121
View File
@@ -1,121 +1,82 @@
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: whwyy * User: whwyy
* Date: 2018/4/3 0003 * Date: 2018/4/3 0003
* Time: 15:42 * Time: 15:42
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
class DateTimeValidator extends BaseValidator class DateTimeValidator extends BaseValidator
{ {
const DATE = 'date'; const string DATE = 'date';
const DATE_TIME = 'datetime'; const string DATE_TIME = 'datetime';
const TIME = 'time'; const string TIME = 'time';
const STR_TO_TIME = 'timestamp'; const string STR_TO_TIME = 'timestamp';
public string $method; public string $method;
/** /**
* @return bool * @param mixed $value
*/ * @return bool
public function trigger(): bool */
{ public function trigger(mixed $value): bool
if (empty($this->params)) { {
return true; return match ($this->method) {
} self::DATE => $this->validatorDate($value),
if (!isset($this->params[$this->field]) || empty($this->params[$this->field])) { self::DATE_TIME => $this->validateDatetime($value),
return true; self::TIME => $this->validatorTime($value),
} self::STR_TO_TIME => $this->validatorTimestamp($value),
return match (strtolower($this->method)) { default => true,
self::DATE => $this->validatorDate($this->params[$this->field]), };
self::DATE_TIME => $this->validateDatetime($this->params[$this->field]), }
self::TIME => $this->validatorTime($this->params[$this->field]),
self::STR_TO_TIME => $this->validatorTimestamp($this->params[$this->field]), /**
default => true, * @param string $value
}; * @return bool
} *
* 效验分秒 格式如 01:02 or 01-02
/** */
* @param $value public function validatorTime(string $value): bool
* @return bool {
* return (bool)preg_match('/^\d{2}:\d{2}(:\d{2})?+(\.\d+)?$/', $value);
* 效验分秒 格式如 01:02 or 01-02 }
*/
public function validatorTime($value): bool
{ /**
if (empty($value) || !is_string($value)) { * @param string $value
return $this->addError('The param :attribute not is a date value'); * @return bool
} *
$match = preg_match('/^[0-5]?\d{1}.{1}[0-5]?\d{1}$/', $value, $result); * 效验分秒 格式如 2017-12-22 01:02
if ($match && $result[0] == $value) { */
return true; public function validateDatetime(string $value): bool
} else { {
return $this->addError('The param :attribute format error'); return (bool)preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?+(\.\d+)?$/', $value);
} }
}
/**
* @param string $value
/** * @return bool
* @param $value *
* @return bool * 效验分秒 格式如 2017-12-22
* */
* 效验分秒 格式如 2017-12-22 01:02 public function validatorDate(string $value): bool
*/ {
public function validateDatetime($value): bool return (bool)preg_match('/^\d{4}-\d{2}-\d{2}$/', $value);
{ }
if (empty($value) || !is_string($value)) {
return $this->addError('The param :attribute not is a date value'); /**
} * @param string|int $value
$match = '/^\d{4}\-\d{2}\-\d{2}\s+\d{2}:\d{2}:\d{2}$/'; * @return bool
$match = preg_match($match, $value, $result); *
if ($match && $result[0] == $value) { * 效验时间戳 格式如 1521452254
return true; */
} else { public function validatorTimestamp(string|int $value): bool
return $this->addError('The param :attribute format error'); {
} return (bool)preg_match('/^1\d{9}$/', $value);
} }
}
/**
* @param $value
* @return bool
*
* 效验分秒 格式如 2017-12-22
*/
public function validatorDate($value): bool
{
if (empty($value) || !is_string($value)) {
return $this->addError('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('The param :attribute format error');
}
}
/**
* @param $value
* @return bool
*
* 效验时间戳 格式如 1521452254
*/
public function validatorTimestamp($value): bool
{
if (empty($value) || !is_numeric($value)) {
return $this->addError('The param :attribute not is a timestamp value');
}
if (strlen((string)$value) != 10) {
return $this->addError('The param :attribute not is a timestamp value');
}
if (!date('YmdHis', $value)) {
return $this->addError('The param :attribute format error');
}
return true;
}
}
+28 -32
View File
@@ -1,32 +1,28 @@
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: whwyy * User: whwyy
* Date: 2018/4/20 0020 * Date: 2018/4/20 0020
* Time: 17:32 * Time: 17:32
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
/**
class EmailValidator extends BaseValidator *
{ */
class EmailValidator extends BaseValidator
/** {
* @return bool
* 检查是否存在 /**
*/ * @param mixed $value
public function trigger(): bool * @return bool
{ * 检查是否存在
if (empty($this->params) || !isset($this->params[$this->field])) { */
return true; public function trigger(mixed $value): bool
} {
if (preg_match('/^[a-zA-Z0-9]+([\.\_]{1,})[a-zA-Z0-9]+@[a-zA-Z]+(\.\w+)+/', $this->params[$this->field])) { return filter_var($value, FILTER_VALIDATE_EMAIL);
return true; }
} else {
return $this->addError('The param :attribute format error'); }
}
}
}
+43 -50
View File
@@ -1,50 +1,43 @@
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: whwyy * User: whwyy
* Date: 2018/4/3 0003 * Date: 2018/4/3 0003
* Time: 15:46 * Time: 15:46
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
class EmptyValidator extends BaseValidator /**
{ *
*/
/** @var string [不能为空] */ class EmptyValidator extends BaseValidator
const CAN_NOT_EMPTY = 'not empty'; {
/** @var string [可为空, 不能为null] */ /** @var string [不能为空] */
const CAN_NOT_NULL = 'not null'; const string CAN_NOT_EMPTY = 'not empty';
public string $method; /** @var string [可为空, 不能为null] */
const string CAN_NOT_NULL = 'not null';
/**
* @return bool public string $method;
*
* 检查参数是否为NULL /**
*/ * @param mixed $value
public function trigger(): bool * @return bool
{ *
if (empty($this->params) || !isset($this->params[$this->field])) { * 检查参数是否为NULL
return $this->addError(':attribute not exists'); */
} public function trigger(mixed $value): bool
switch (strtolower($this->method)) { {
case self::CAN_NOT_EMPTY: return match ($this->method) {
if (strlen($this->params[$this->field]) < 1) { self::CAN_NOT_NULL => !is_null($value),
return $this->addError('The :attribute can not empty.'); self::CAN_NOT_EMPTY => !empty($value),
} default => true
break; };
case self::CAN_NOT_NULL: }
if ($this->params[$this->field] === null) { }
return $this->addError('The :attribute can not is null.');
}
break;
}
return true;
}
}
+24 -43
View File
@@ -1,43 +1,24 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
/**
/** * Class EnumValidator
* Class EnumValidator * @package validator
* @package validator */
*/ class EnumValidator extends BaseValidator
class EnumValidator extends BaseValidator {
{
/**
public array $value = []; * @param mixed $value
* @return bool
/** */
* @return bool public function trigger(mixed $value): bool
*/ {
public function trigger(): bool return in_array($value, $this->value);
{ }
if (empty($this->params) || !isset($this->params[$this->field])) {
return $this->addError('The param :attribute is null'); }
}
if (is_null($this->params[$this->field])) {
return $this->addError('The param :attribute is null');
}
if (!in_array($this->params[$this->field], $this->value)) {
return $this->addError($this->i());
}
return true;
}
/**
* @return string
*/
private function i(): string
{
return 'The param :attribute value only in ' . implode(',', $this->value);
}
}
+27 -38
View File
@@ -1,38 +1,27 @@
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: whwyy * User: whwyy
* Date: 2018/4/4 0004 * Date: 2018/4/4 0004
* Time: 18:44 * Time: 18:44
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
class IntegerValidator extends BaseValidator /**
{ *
*/
const MIN = 'min'; class IntegerValidator extends BaseValidator
const MAX = 'max'; {
public ?int $value = null; /**
private string $type = ''; * @param float $value
* @return bool
/** */
* @return bool public function trigger(mixed $value): bool
*/ {
public function trigger(): bool return (float)$value == $value;
{ }
if (empty($this->params) || !isset($this->params[$this->field])) { }
return true;
}
if ($this->type !== self::MIN && $this->params[$this->field] < $this->value) {
return $this->addError('The ' . $this->field . ' cannot be less than the default value.');
}
if ($this->type !== self::MAX && $this->params[$this->field] > $this->value) {
return $this->addError('The ' . $this->field . ' cannot be greater than the default value.');
}
return true;
}
}
+69 -110
View File
@@ -1,110 +1,69 @@
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: whwyy * User: whwyy
* Date: 2018/4/3 0003 * Date: 2018/4/3 0003
* Time: 17:04 * Time: 17:04
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
class LengthValidator extends BaseValidator class LengthValidator extends BaseValidator
{ {
const MAX_LENGTH = 'max'; const string MAX_LENGTH = 'max';
const MIN_LENGTH = 'min'; const string MIN_LENGTH = 'min';
public string $method; /**
* @var string
public int $value; */
public string $method = 'default';
/**
* @return bool /**
*/ * @param mixed $value
public function trigger(): bool * @return bool
{ */
if (empty($this->params) || !isset($this->params[$this->field])) { public function trigger(mixed $value): bool
if ($this->method != self::MAX_LENGTH) { {
return $this->addError('The param :attribute not exists'); return match ($this->method) {
} else { self::MAX_LENGTH => $this->maxLength((string)$value),
return TRUE; self::MIN_LENGTH => $this->minLength((string)$value),
} default => $this->defaultLength((string)$value),
} };
return match (strtolower($this->method)) { }
self::MAX_LENGTH => $this->maxLength($this->params[$this->field]),
self::MIN_LENGTH => $this->minLength($this->params[$this->field]), /**
default => $this->defaultLength($this->params[$this->field]), * @param string $value
}; * @return bool
} *
* 效验长度是否大于最大长度
/** */
* @param $value private function maxLength(string $value): bool
* @return bool {
* return mb_strlen($value) <= $this->value;
* 效验长度是否大于最大长度 }
*/
private function maxLength($value): bool /**
{ * @param string $value
if (is_array($value)) { * @return bool
if (count($value) > $value) { *
return $this->addError('The param :attribute length overflow'); * 效验长度是否小于最小长度
} */
} else { private function minLength(string $value): bool
if (is_numeric($value) && strlen((string)$value) > $this->value) { {
return $this->addError('The param :attribute length overflow'); return mb_strlen($value) >= $this->value;
} }
if (strlen($value) > $this->value) {
return $this->addError('The param :attribute length overflow'); /**
} * @param string $value
} * @return bool
return TRUE; *
} * 效验长度是否小于最小长度
*/
/** private function defaultLength(string $value): bool
* @param $value {
* @return bool return mb_strlen($value) == $this->value;
* }
* 效验长度是否小于最小长度 }
*/
private function minLength($value): bool
{
if (is_array($value)) {
if (count($value) < $value) {
return $this->addError('The param :attribute length error');
}
} else {
if (is_numeric($value) && strlen((string)$value) < $this->value) {
return $this->addError('The param :attribute length overflow');
}
if (strlen($value) < $this->value) {
return $this->addError('The param :attribute length error');
}
}
return TRUE;
}
/**
* @param $value
* @return bool
*
* 效验长度是否小于最小长度
*/
private function defaultLength($value): bool
{
if (is_array($value)) {
if (count($value) !== $value) {
return $this->addError('The param :attribute length error');
}
} else {
if (is_numeric($value) && strlen((string)$value) !== $this->value) {
return $this->addError('The param :attribute length overflow');
}
if (mb_strlen($value) !== $this->value) {
return $this->addError('The param :attribute length error; ' . mb_strlen($value) . ':' . $this->value);
}
}
return TRUE;
}
}
+26 -29
View File
@@ -1,29 +1,26 @@
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: whwyy * User: whwyy
* Date: 2018/4/3 0003 * Date: 2018/4/3 0003
* Time: 15:47 * Time: 15:47
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
class RequiredValidator extends BaseValidator class RequiredValidator extends BaseValidator
{ {
/** /**
* @return bool * @param mixed $value
* 检查是否存在 * @return bool
*/ * 检查是否存在
public function trigger(): bool */
{ public function trigger(mixed $value): bool
if (!isset($this->params[$this->field])) { {
return $this->addError('The param :attribute not exists'); return !is_null($value);
} else { }
return true;
} }
}
}
+26 -34
View File
@@ -1,34 +1,26 @@
<?php <?php
namespace validator; namespace validator;
use Exception; /**
* Class RoundValidator
/** * @package validator
* Class RoundValidator */
* @package validator class RoundValidator extends BaseValidator
*/ {
class RoundValidator extends BaseValidator
{ /**
* @param string $field
* @param mixed $value
public ?int $value = null; * @return bool
* @throws
*/
/** public function trigger(mixed $value): bool
* @return bool {
* @throws Exception return round($value, $this->value) == $value;
*/ }
public function trigger(): bool
{
$value = $this->model->getAttribute($this->field); }
if ($value == null || round($value, $this->value) != $value) {
return $this->addError('The param :attribute length error');
}
return true;
}
}
+89 -141
View File
@@ -1,141 +1,89 @@
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: whwyy * User: whwyy
* Date: 2018/4/4 0004 * Date: 2018/4/4 0004
* Time: 18:44 * Time: 18:44
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
class TypesOfValidator extends BaseValidator use function json_validate;
{
class TypesOfValidator extends BaseValidator
{
const JSON = 'json';
const FLOAT = 'float';
const ARRAY = 'array'; const string JSON = 'json';
const STRING = 'string'; const string FLOAT = 'float';
const INTEGER = 'integer'; const string ARRAY = 'array';
const SERIALIZE = 'serialize'; const string STRING = 'string';
const string INTEGER = 'integer';
private ?int $min = null;
private ?int $max = null; /** @var string */
public string $method;
/** @var array */
public array $types = [ /**
self::JSON => 'json', * @param string $field
self::FLOAT => 'float', * @param mixed $value
self::ARRAY => 'array', * @return bool
self::STRING => 'string', */
self::INTEGER => 'integer', public function trigger(mixed $value): bool
self::SERIALIZE => 'serialize', {
]; return match ($this->method) {
self::INTEGER => $this->integerFormat($value),
/** @var string */ self::FLOAT => $this->floatFormat($value),
public string $method; self::JSON => $this->jsonFormat($value),
self::STRING => $this->stringFormat($value),
self::ARRAY => $this->arrayFormat($value),
/** };
* @return bool }
*/
public function trigger(): bool /**
{ * @param string|null $value
if (!in_array($this->method, $this->types)) { * @return bool
return true; */
} public function jsonFormat(?string $value): bool
if (empty($this->params) || !isset($this->params[$this->field])) { {
return true; return json_validate($value);
} }
if ($this->params[$this->field] === null) {
return $this->addError('This ' . $this->field . ' is not an empty data.'); /**
} * @param mixed $value
return $this->{$this->method . 'Format'}($this->params[$this->field]); * @return bool
} */
public function arrayFormat(mixed $value): bool
/** {
* @param $value return is_array($value);
* @return bool }
*/
public function jsonFormat($value): bool /**
{ * @param mixed $value
if (!is_string($value) || is_numeric($value)) { * @return bool
return $this->addError('The ' . $this->field . ' not is JSON data.'); */
} public function stringFormat(mixed $value): bool
if (is_null(json_decode($value))) { {
return $this->addError('The ' . $this->field . ' not is JSON data.'); return is_string($value);
} }
return true;
} /**
* @param mixed $value
/** * @return bool
* @param $value */
* @return bool public function integerFormat(mixed $value): bool
*/ {
public function serializeFormat($value): bool return (int)$value == $value;
{ }
if (!is_string($value) || is_numeric($value)) {
return $this->addError('The ' . $this->field . ' not is serialize data.'); /**
} * @param mixed $value
if (false === swoole_unserialize($value)) { * @return bool
return $this->addError('The ' . $this->field . ' not is serialize data.'); */
} public function floatFormat(mixed $value): bool
return true; {
} return (float)$value == $value;
}
/**
* @param $value }
* @return bool
*/
public function arrayFormat($value): bool
{
if (!is_array($value)) {
return $this->addError('The ' . $this->field . ' not is array data.');
}
return true;
}
/**
* @param $value
* @return bool
*/
public function stringFormat($value): bool
{
if (is_array($value) || is_object($value) || is_bool($value)) {
return $this->addError('The ' . $this->field . ' not is string data.');
}
return true;
}
/**
* @param $value
* @return bool
*/
public function integerFormat($value): bool
{
if (!is_numeric($value)) {
return $this->addError('The ' . $this->field . ' not is number data.');
}
if ((int)$value != $value) {
return $this->addError('The ' . $this->field . ' not is number data.');
}
return true;
}
/**
* @param $value
* @return bool
*/
public function floatFormat($value): bool
{
$trim = (float)$value;
if ($trim != $value || !is_float($trim)) {
return $this->addError('The ' . $this->field . ' not is float data.');
}
return true;
}
}
+42 -41
View File
@@ -1,41 +1,42 @@
<?php <?php
/** /**
* Created by PhpStorm. * Created by PhpStorm.
* User: qv * User: qv
* Date: 2018/10/16 0016 * Date: 2018/10/16 0016
* Time: 10:24 * Time: 10:24
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
class UniqueValidator extends BaseValidator use Database\ModelInterface;
{
class UniqueValidator extends BaseValidator
/** {
* @return bool
* @throws
* 检查是否存在 /**
*/ * @var ModelInterface
public function trigger(): bool */
{ public ModelInterface $model;
$param = $this->getParams();
if (empty($param) || !isset($param[$this->field])) {
return TRUE; /**
} * @var string
*/
if (empty($this->model)) { public string $field;
return $this->addError('Model error.');
} /**
if (!$this->model->getIsNowExample()) { * @param mixed $value
return true; * @return bool
} * @throws
if ($this->model::query()->where([$this->field => $param[$this->field]])->exists()) { * 检查是否存在
return $this->addError('The :attribute \'' . $param[$this->field] . '\' is exists!'); */
} public function trigger(mixed $value): bool
return $this->isFail = TRUE; {
} return $this->model::query()->where([$this->field => $value])->exists() === false;
}
}
}
+117 -221
View File
@@ -1,221 +1,117 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
use Closure; use Database\ModelInterface;
use Exception; use Kiri;
use Kiri\Kiri;
/**
/** * Class Validator
* Class Validator * @package validator
* @package validator */
*/ class Validator extends BaseValidator
class Validator extends BaseValidator {
{
/**
/** @var BaseValidator[] */ * classMap
private ?array $validators = []; */
const array classMap = [
/** @var ?Validator */ 'not empty' => ['class' => EmptyValidator::class, 'method' => EmptyValidator::CAN_NOT_EMPTY,],
private static ?Validator $instance = null; 'not null' => ['class' => EmptyValidator::class, 'method' => EmptyValidator::CAN_NOT_NULL,],
'required' => ['class' => RequiredValidator::class,],
protected array $classMap = [ 'enum' => ['class' => EnumValidator::class,],
'not empty' => [ 'unique' => ['class' => UniqueValidator::class,],
'class' => 'validator\EmptyValidator', 'datetime' => ['class' => DateTimeValidator::class, 'method' => DateTimeValidator::DATE_TIME,],
'method' => EmptyValidator::CAN_NOT_EMPTY, 'date' => ['class' => DateTimeValidator::class, 'method' => DateTimeValidator::DATE,],
], 'time' => ['class' => DateTimeValidator::class, 'method' => DateTimeValidator::TIME,],
'not null' => [ 'timestamp' => ['class' => DateTimeValidator::class, 'method' => DateTimeValidator::STR_TO_TIME,],
'class' => 'validator\EmptyValidator', 'string' => ['class' => TypesOfValidator::class, 'method' => TypesOfValidator::STRING,],
'method' => EmptyValidator::CAN_NOT_NULL, 'int' => ['class' => TypesOfValidator::class, 'method' => TypesOfValidator::INTEGER,],
], 'min' => ['class' => IntegerValidator::class],
'required' => [ 'max' => ['class' => IntegerValidator::class],
'class' => 'validator\RequiredValidator', 'json' => ['class' => TypesOfValidator::class, 'method' => TypesOfValidator::JSON,],
], 'float' => ['class' => TypesOfValidator::class, 'method' => TypesOfValidator::FLOAT,],
'enum' => [ 'array' => ['class' => TypesOfValidator::class, 'method' => TypesOfValidator::ARRAY,],
'class' => 'validator\EnumValidator', 'maxLength' => ['class' => LengthValidator::class, 'method' => LengthValidator::MAX_LENGTH,],
], 'minLength' => ['class' => LengthValidator::class, 'method' => LengthValidator::MIN_LENGTH,],
'unique' => [ 'email' => ['class' => EmailValidator::class],
'class' => 'validator\UniqueValidator', 'length' => ['class' => LengthValidator::class],
], 'round' => ['class' => RoundValidator::class,],
'datetime' => [ ];
'class' => 'validator\DatetimeValidator',
'method' => DateTimeValidator::DATE_TIME, /** @var BaseValidator[] */
], private ?array $validators = [];
'date' => [
'class' => 'validator\DatetimeValidator',
'method' => DateTimeValidator::DATE, /**
], * @param ModelInterface $model
'time' => [ * @param array $fields
'class' => 'validator\DatetimeValidator', * @param array $rules
'method' => DateTimeValidator::TIME, * @return $this
], */
'timestamp' => [ public function make(ModelInterface $model, array $fields, array $rules): static
'class' => 'validator\DatetimeValidator', {
'method' => DateTimeValidator::STR_TO_TIME, foreach ($fields as $field) {
], if (!isset($this->validators[$field])) {
'string' => [ $this->validators[$field] = [];
'class' => 'validator\TypesOfValidator', }
'method' => TypesOfValidator::STRING, foreach ($rules as $key => $val) {
], if (is_numeric($key) && method_exists($model, $val)) {
'int' => [ $this->validators[$field][] = [$model, $val];
'class' => 'validator\TypesOfValidator', } else {
'method' => TypesOfValidator::INTEGER, $this->validators[$field][] = $this->mapGen($model, $field, $key, $val);
], }
'min' => [ }
'class' => IntegerValidator::class }
], return $this;
'max' => [ }
'class' => IntegerValidator::class
],
'json' => [ /**
'class' => 'validator\TypesOfValidator', * @param ModelInterface $model
'method' => TypesOfValidator::JSON, * @param $key
], * @param $val
'float' => [ * @return array
'class' => 'validator\TypesOfValidator', * @throws
'method' => TypesOfValidator::FLOAT, */
], protected function mapGen(ModelInterface $model, $field, $key, $val): array
'array' => [ {
'class' => 'validator\TypesOfValidator', if (is_numeric($key)) {
'method' => TypesOfValidator::ARRAY, $defined = self::classMap[$val];
], } else {
'serialize' => [ $defined = self::classMap[$key];
'class' => 'validator\TypesOfValidator', $defined['value'] = $val;
'method' => TypesOfValidator::SERIALIZE, }
], if ($defined['class'] == UniqueValidator::class) {
'maxLength' => [ $defined['model'] = $model;
'class' => 'validator\LengthValidator', $defined['field'] = $field;
'method' => 'max', }
], return [Kiri::createObject($defined), 'trigger'];
'minLength' => [ }
'class' => 'validator\LengthValidator',
'method' => 'min',
], /**
'email' => [ * @param array $attributes
'class' => 'validator\EmailValidator', * @return bool
'method' => 'email', */
], public function validation(array $attributes): bool
'length' => [ {
'class' => 'validator\LengthValidator', if (count($this->validators) < 1) {
'method' => 'default', return true;
], }
'round' => [ foreach ($attributes as $field => $attribute) {
'class' => 'validator\RoundValidator', if (isset($this->validators[$field])) {
], $validator = $this->validators[$field];
]; foreach ($validator as $value) {
if (!call_user_func($value, $attribute)) {
/** return $this->addError($field, 'field :attribute data format error.');
* @return Validator|null }
*/ }
public static function getInstance(): ?Validator }
{ }
if (static::$instance == null) { return true;
static::$instance = new Validator(); }
} }
return static::$instance;
}
/**
* @param $field
* @param $rules
* @return $this
* @throws Exception
*/
public function make($field, $rules): static
{
if (!is_array($field)) {
$field = [$field];
}
$param = $this->getParams();
$model = $this->getModel();
foreach ($field as $val) {
$this->createRule($val, $rules, $model, $param);
}
return $this;
}
/**
* @param $field
* @param $rule
* @param $model
* @param $param
* @throws Exception
* ['maxLength'=>150, 'required', 'minLength' => 100]
*/
public function createRule($field, $rule, $model, $param)
{
$define = ['field' => $field];
$is_model = is_null($model);
foreach ($rule as $key => $val) {
if (!$is_model) {
if (is_string($val) && method_exists($model, $val)) {
$this->validators[] = [$model, $val];
continue;
}
}
if (is_string($key)) {
$type = strtolower($key);
$define['value'] = $val;
} else {
$type = strtolower($val);
}
if (!isset($this->classMap[$type])) {
continue;
}
$this->validators[] = array_merge($this->classMap[$type], $define, [
'params' => $param,
'model' => $model
]);
}
}
/**
* @return bool
* @throws Exception
*/
public function validation(): bool
{
if (count($this->validators) < 1) {
return true;
}
foreach ($this->validators as $val) {
[$result, $validator] = $this->check($val);
if ($result === true) {
continue;
}
$isTrue = false;
if ($validator instanceof BaseValidator) {
$this->addError($validator->getError());
}
break;
}
$this->validators = [];
return !isset($isTrue);
}
/**
* @param BaseValidator|array|Closure $val
* @return mixed
* @throws Exception
*/
private function check(BaseValidator|array|Closure $val): mixed
{
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];
}
}
+2 -2
View File
@@ -15,8 +15,8 @@
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"validator\\": "src/" "validator\\": "./"
} }
}, },
"require-dev": { "require-dev": {
} }