6 Commits

Author SHA1 Message Date
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
as2252258 84c345375b Revert "改名"
This reverts commit fdf58326
2022-01-08 18:49:06 +08:00
as2252258 00a53ba0f3 Revert "改名"
This reverts commit fdf58326
2022-01-04 16:53:31 +08:00
as2252258 011e0cd9b8 1 2021-12-12 06:06:15 +08:00
16 changed files with 1101 additions and 1149 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
+69 -70
View File
@@ -1,70 +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: 15:28 * Time: 15:28
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
/** /**
* Class ArrayValidator * Class ArrayValidator
* @package validator * @package validator
*/ */
class ArrayValidator extends BaseValidator class ArrayValidator extends BaseValidator
{ {
/** /**
* @return bool * @return bool
* *
* 检查 * 检查
*/ */
public function trigger(): bool public function trigger(): bool
{ {
$param = $this->getParams(); if (empty($this->params)) {
if (empty($param) || !is_array($param)) { return true;
return true; }
} if (!isset($this->params[$this->field])) {
if (!isset($param[$this->field])) { return true;
return true; }
} if (!is_array($this->params[$this->field])) {
if (!is_array($param[$this->field])) { return $this->addError("The param :attribute must a array");
return $this->addError("The param :attribute must a array"); }
} return true;
return true; }
}
/**
/** * @param $data
* @param $data * @return array
* @return array *
* * 转成数组
* 转成数组 */
*/ private function toArray($data): array
private function toArray($data): array {
{ if (is_numeric($data)) {
if (is_numeric($data)) { return [];
return []; } else if (is_null(json_decode($data, true))) {
} else if (is_null(json_decode($data, true))) { return [];
return []; } elseif (is_object($data)) {
} elseif (is_object($data)) { $data = get_object_vars($data);
$data = get_object_vars($data); }
}
$_tmp = [];
$_tmp = []; foreach ($data as $key => $val) {
foreach ($data as $key => $val) { if (is_object($val)) {
if (is_object($val)) { $_tmp[$key] = $this->toArray($val);
$_tmp[$key] = $this->toArray($val); } else if (is_array($val)) {
} else if (is_array($val)) { $_tmp[$key] = $this->toArray($val);
$_tmp[$key] = $this->toArray($val); } else {
} else { $_tmp[$key] = $val;
$_tmp[$key] = $val; }
} }
}
return $_tmp;
return $_tmp; }
}
}
}
+137 -137
View File
@@ -1,137 +1,137 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
use Database\Model; use Database\Model;
use Exception; use Exception;
abstract class BaseValidator abstract class BaseValidator
{ {
public string $field = ''; public string $field = '';
public array $rules = []; public array $rules = [];
public string $method; public string $method;
protected bool $isFail = TRUE; protected bool $isFail = TRUE;
protected string $message = ''; protected string $message = '';
protected array $params = []; protected array $params = [];
protected ?Model $model = null; protected ?Model $model = null;
/** /**
* @param $model * @param $model
*/ */
public function setModel($model) public function setModel($model)
{ {
$this->model = $model; $this->model = $model;
} }
/** /**
* @return Model|null * @return Model|null
*/ */
public function getModel(): ?Model public function getModel(): ?Model
{ {
return $this->model; return $this->model;
} }
/** /**
* BaseValidator constructor. * BaseValidator constructor.
* @param array $config * @param array $config
*/ */
public function __construct(array $config = []) public function __construct(array $config = [])
{ {
$this->regConfig($config); $this->regConfig($config);
} }
/** /**
* @param $config * @param $config
*/ */
private function regConfig($config) private function regConfig($config)
{ {
if (empty($config) || !is_array($config)) { if (empty($config) || !is_array($config)) {
return; return;
} }
foreach ($config as $key => $val) { foreach ($config as $key => $val) {
$this->$key = $val; $this->$key = $val;
} }
} }
/** /**
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function trigger(): bool public function trigger(): bool
{ {
throw new Exception('Child Class must define method of trigger'); throw new Exception('Child Class must define method of trigger');
} }
/** /**
* @return array * @return array
*/ */
protected function getParams(): array protected function getParams(): array
{ {
return $this->params; return $this->params;
} }
/** /**
* @param array|null $data * @param array|null $data
* @return $this * @return $this
*/ */
public function setParams(?array $data): static public function setParams(?array $data): static
{ {
if (is_null($data)) { if (is_null($data)) {
$data = []; $data = [];
} }
$this->params = $data; $this->params = $data;
return $this; return $this;
} }
/** /**
* @param $message * @param $message
* @return bool * @return bool
*/ */
public function addError($message): bool public function addError($message): bool
{ {
$this->isFail = FALSE; $this->isFail = FALSE;
$message = str_replace(':attribute', $this->field, $message); $message = str_replace(':attribute', $this->field, $message);
$this->message = $message; $this->message = $message;
return $this->isFail; return $this->isFail;
} }
/** /**
* @return string * @return string
*/ */
public function getError(): string public function getError(): string
{ {
return $this->message; return $this->message;
} }
/** /**
* @param $name * @param $name
* @param $value * @param $value
* @throws Exception * @throws Exception
*/ */
public function __set($name, $value) public function __set($name, $value)
{ {
$method = 'set' . ucfirst($name); $method = 'set' . ucfirst($name);
if (method_exists($this, $method)) { if (method_exists($this, $method)) {
$this->$method($value); $this->$method($value);
} else if (property_exists($this, $name)) { } else if (property_exists($this, $name)) {
$this->$name = $value; $this->$name = $value;
} else { } else {
throw new Exception('unknown property ' . $name . ' in class ' . static::class); throw new Exception('unknown property ' . $name . ' in class ' . static::class);
} }
} }
} }
@@ -1,128 +1,121 @@
<?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 DATE = 'date';
const DATE_TIME = 'datetime'; const DATE_TIME = 'datetime';
const TIME = 'time'; const TIME = 'time';
const STR_TO_TIME = 'timestamp'; const STR_TO_TIME = 'timestamp';
public string $method; public string $method;
/** /**
* @return bool * @return bool
*/ */
public function trigger(): bool public function trigger(): bool
{ {
$param = $this->getParams(); if (empty($this->params)) {
if (empty($param) || !is_array($param)) { return true;
return true; }
} if (!isset($this->params[$this->field]) || empty($this->params[$this->field])) {
if (!isset($param[$this->field]) || empty($param[$this->field])) { return true;
return true; }
} return match (strtolower($this->method)) {
$value = $param[$this->field]; self::DATE => $this->validatorDate($this->params[$this->field]),
switch (strtolower($this->method)) { self::DATE_TIME => $this->validateDatetime($this->params[$this->field]),
case self::DATE: self::TIME => $this->validatorTime($this->params[$this->field]),
return $this->validatorDate($value); self::STR_TO_TIME => $this->validatorTimestamp($this->params[$this->field]),
case self::DATE_TIME: default => true,
return $this->validateDatetime($value); };
case self::TIME: }
return $this->validatorTime($value);
case self::STR_TO_TIME: /**
return $this->validatorTimestamp($value); * @param $value
default: * @return bool
return true; *
} * 效验分秒 格式如 01:02 or 01-02
} */
public function validatorTime($value): bool
/** {
* @param $value if (empty($value) || !is_string($value)) {
* @return bool return $this->addError('The param :attribute not is a date value');
* }
* 效验分秒 格式如 01:02 or 01-02 $match = preg_match('/^[0-5]?\d{1}.{1}[0-5]?\d{1}$/', $value, $result);
*/ if ($match && $result[0] == $value) {
public function validatorTime($value): bool return true;
{ } else {
if (empty($value) || !is_string($value)) { return $this->addError('The param :attribute format error');
return $this->addError('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 { * @param $value
return $this->addError('The param :attribute format error'); * @return bool
} *
} * 效验分秒 格式如 2017-12-22 01:02
*/
public function validateDatetime($value): bool
/** {
* @param $value if (empty($value) || !is_string($value)) {
* @return bool return $this->addError('The param :attribute not is a date value');
* }
* 效验分秒 格式如 2017-12-22 01:02 $match = '/^\d{4}\-\d{2}\-\d{2}\s+\d{2}:\d{2}:\d{2}$/';
*/ $match = preg_match($match, $value, $result);
public function validateDatetime($value): bool if ($match && $result[0] == $value) {
{ return true;
if (empty($value) || !is_string($value)) { } else {
return $this->addError('The param :attribute not is a date value'); return $this->addError('The param :attribute format error');
} }
$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; * @param $value
} else { * @return bool
return $this->addError('The param :attribute format error'); *
} * 效验分秒 格式如 2017-12-22
} */
public function validatorDate($value): bool
/** {
* @param $value if (empty($value) || !is_string($value)) {
* @return bool return $this->addError('The param :attribute not is a date value');
* }
* 效验分秒 格式如 2017-12-22 $match = preg_match('/^(\d{4}).*([0-12]).*([0-31]).*$/', $value, $result);
*/ if ($match && $result[0] == $value) {
public function validatorDate($value): bool return true;
{ } else {
if (empty($value) || !is_string($value)) { return $this->addError('The param :attribute format error');
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; * @param $value
} else { * @return bool
return $this->addError('The param :attribute format error'); *
} * 效验时间戳 格式如 1521452254
} */
public function validatorTimestamp($value): bool
/** {
* @param $value if (empty($value) || !is_numeric($value)) {
* @return bool return $this->addError('The param :attribute not is a timestamp value');
* }
* 效验时间戳 格式如 1521452254 if (strlen((string)$value) != 10) {
*/ return $this->addError('The param :attribute not is a timestamp value');
public function validatorTimestamp($value): bool }
{ if (!date('YmdHis', $value)) {
if (empty($value) || !is_numeric($value)) { return $this->addError('The param :attribute format error');
return $this->addError('The param :attribute not is a timestamp value'); }
} return true;
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;
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/20 0020
* Time: 17:32
*/
declare(strict_types=1);
namespace validator;
class EmailValidator extends BaseValidator
{
/**
* @return bool
* 检查是否存在
*/
public function trigger(): bool
{
if (empty($this->params) || !isset($this->params[$this->field])) {
return true;
}
if (preg_match('/^[a-zA-Z0-9]+([\.\_]{1,})[a-zA-Z0-9]+@[a-zA-Z]+(\.\w+)+/', $this->params[$this->field])) {
return true;
} else {
return $this->addError('The param :attribute format error');
}
}
}
+50 -55
View File
@@ -1,55 +1,50 @@
<?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 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
* *
* 检查参数是否为NULL * 检查参数是否为NULL
*/ */
public function trigger(): bool public function trigger(): bool
{ {
$param = $this->getParams(); if (empty($this->params) || !isset($this->params[$this->field])) {
if (empty($param) || !isset($param[$this->field])) { return $this->addError(':attribute not exists');
return $this->addError(':attribute not exists'); }
} switch (strtolower($this->method)) {
case self::CAN_NOT_EMPTY:
$value = $param[$this->field]; if (strlen($this->params[$this->field]) < 1) {
return $this->addError('The :attribute can not empty.');
switch (strtolower($this->method)) { }
case self::CAN_NOT_EMPTY: break;
if (strlen($value) < 1) { case self::CAN_NOT_NULL:
return $this->addError('The :attribute can not empty.'); if ($this->params[$this->field] === null) {
} return $this->addError('The :attribute can not is null.');
break; }
case self::CAN_NOT_NULL: break;
if ($value === null) { }
return $this->addError('The :attribute can not is null.'); return true;
} }
break; }
}
return true;
}
}
+43 -50
View File
@@ -1,50 +1,43 @@
<?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 = []; public array $value = [];
/** /**
* @return bool * @return bool
*/ */
public function trigger(): bool public function trigger(): bool
{ {
$param = $this->getParams(); if (empty($this->params) || !isset($this->params[$this->field])) {
if (empty($param) || !isset($param[$this->field])) { return $this->addError('The param :attribute is null');
return $this->addError('The param :attribute is null'); }
} if (is_null($this->params[$this->field])) {
$value = $param[$this->field]; return $this->addError('The param :attribute is null');
if (is_null($value)) { }
return $this->addError('The param :attribute is null'); if (!in_array($this->params[$this->field], $this->value)) {
} return $this->addError($this->i());
}
if (!is_array($this->value)) { return true;
return true; }
}
if (!in_array($value, $this->value)) { /**
return $this->addError($this->i()); * @return string
} */
private function i(): string
return true; {
} return 'The param :attribute value only in ' . implode(',', $this->value);
}
/**
* @return string }
*/
private function i(): string
{
return 'The param :attribute value only in ' . implode(',', $this->value);
}
}
@@ -1,45 +1,38 @@
<?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 class IntegerValidator extends BaseValidator
{ {
const MIN = 'min'; const MIN = 'min';
const MAX = 'max'; const MAX = 'max';
public ?int $value = null; public ?int $value = null;
private string $type = ''; private string $type = '';
/** /**
* @return bool * @return bool
*/ */
public function trigger(): bool public function trigger(): bool
{ {
$param = $this->getParams(); if (empty($this->params) || !isset($this->params[$this->field])) {
if (empty($param) || !isset($param[$this->field])) { return true;
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.');
$value = $param[$this->field] ?? null; }
if ($value === null) { if ($this->type !== self::MAX && $this->params[$this->field] > $this->value) {
return $this->addError('The :attribute can not is null.'); return $this->addError('The ' . $this->field . ' cannot be greater than the default value.');
} }
if ($this->type !== self::MIN && $value < $this->value) { return true;
return $this->addError('The ' . $this->field . ' cannot be less than the default value.'); }
} }
if ($this->type !== self::MAX && $value > $this->value) {
return $this->addError('The ' . $this->field . ' cannot be greater than the default value.');
}
return true;
}
}
+110 -115
View File
@@ -1,115 +1,110 @@
<?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 MAX_LENGTH = 'max';
const MIN_LENGTH = 'min'; const MIN_LENGTH = 'min';
public string $method; public string $method;
public int $value; public int $value;
/** /**
* @return bool * @return bool
*/ */
public function trigger(): bool public function trigger(): bool
{ {
$param = $this->getParams(); if (empty($this->params) || !isset($this->params[$this->field])) {
if (empty($param) || !isset($param[$this->field])) { if ($this->method != self::MAX_LENGTH) {
if ($this->method != self::MAX_LENGTH) { return $this->addError('The param :attribute not exists');
return $this->addError('The param :attribute not exists'); } else {
} else { return TRUE;
return TRUE; }
} }
} return match (strtolower($this->method)) {
$value = $param[$this->field]; self::MAX_LENGTH => $this->maxLength($this->params[$this->field]),
if (is_null($value)) { self::MIN_LENGTH => $this->minLength($this->params[$this->field]),
return $this->addError('The param :attribute is null'); default => $this->defaultLength($this->params[$this->field]),
} };
return match (strtolower($this->method)) { }
self::MAX_LENGTH => $this->maxLength($value),
self::MIN_LENGTH => $this->minLength($value), /**
default => $this->defaultLength($value), * @param $value
}; * @return bool
} *
* 效验长度是否大于最大长度
/** */
* @param $value private function maxLength($value): bool
* @return bool {
* if (is_array($value)) {
* 效验长度是否大于最大长度 if (count($value) > $value) {
*/ return $this->addError('The param :attribute length overflow');
private function maxLength($value): bool }
{ } else {
if (is_array($value)) { if (is_numeric($value) && strlen((string)$value) > $this->value) {
if (count($value) > $value) { return $this->addError('The param :attribute length overflow');
return $this->addError('The param :attribute length overflow'); }
} if (strlen($value) > $this->value) {
} else { return $this->addError('The param :attribute length overflow');
if (is_numeric($value) && strlen((string)$value) > $this->value) { }
return $this->addError('The param :attribute length overflow'); }
} return TRUE;
if (strlen($value) > $this->value) { }
return $this->addError('The param :attribute length overflow');
} /**
} * @param $value
return TRUE; * @return bool
} *
* 效验长度是否小于最小长度
/** */
* @param $value private function minLength($value): bool
* @return bool {
* if (is_array($value)) {
* 效验长度是否小于最小长度 if (count($value) < $value) {
*/ return $this->addError('The param :attribute length error');
private function minLength($value): bool }
{ } else {
if (is_array($value)) { if (is_numeric($value) && strlen((string)$value) < $this->value) {
if (count($value) < $value) { return $this->addError('The param :attribute length overflow');
return $this->addError('The param :attribute length error'); }
} if (strlen($value) < $this->value) {
} else { return $this->addError('The param :attribute length error');
if (is_numeric($value) && strlen((string)$value) < $this->value) { }
return $this->addError('The param :attribute length overflow'); }
} return TRUE;
if (strlen($value) < $this->value) { }
return $this->addError('The param :attribute length error');
} /**
} * @param $value
return TRUE; * @return bool
} *
* 效验长度是否小于最小长度
/** */
* @param $value private function defaultLength($value): bool
* @return bool {
* if (is_array($value)) {
* 效验长度是否小于最小长度 if (count($value) !== $value) {
*/ return $this->addError('The param :attribute length error');
private function defaultLength($value): bool }
{ } else {
if (is_array($value)) { if (is_numeric($value) && strlen((string)$value) !== $this->value) {
if (count($value) !== $value) { return $this->addError('The param :attribute length overflow');
return $this->addError('The param :attribute length error'); }
} if (mb_strlen($value) !== $this->value) {
} else { return $this->addError('The param :attribute length error; ' . mb_strlen($value) . ':' . $this->value);
if (is_numeric($value) && strlen((string)$value) !== $this->value) { }
return $this->addError('The param :attribute length overflow'); }
} return TRUE;
if (mb_strlen($value) !== $this->value) { }
return $this->addError('The param :attribute length error; ' . mb_strlen($value) . ':' . $this->value); }
}
}
return TRUE;
}
}
@@ -1,30 +1,29 @@
<?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 * @return bool
* 检查是否存在 * 检查是否存在
*/ */
public function trigger(): bool public function trigger(): bool
{ {
$param = $this->getParams(); if (!isset($this->params[$this->field])) {
if (!is_array($param) || !isset($param[$this->field])) { return $this->addError('The param :attribute not exists');
return $this->addError('The param :attribute not exists'); } else {
} else { return true;
return true; }
} }
}
}
}
+34 -34
View File
@@ -1,34 +1,34 @@
<?php <?php
namespace validator; namespace validator;
use Exception; use Exception;
/** /**
* Class RoundValidator * Class RoundValidator
* @package validator * @package validator
*/ */
class RoundValidator extends BaseValidator class RoundValidator extends BaseValidator
{ {
public ?int $value = null; public ?int $value = null;
/** /**
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public function trigger(): bool public function trigger(): bool
{ {
$value = $this->model->getAttribute($this->field); $value = $this->model->getAttribute($this->field);
if ($value == null || round($value, $this->value) != $value) { if ($value == null || round($value, $this->value) != $value) {
return $this->addError('The param :attribute length error'); return $this->addError('The param :attribute length error');
} }
return true; return true;
} }
} }
+141 -149
View File
@@ -1,149 +1,141 @@
<?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 class TypesOfValidator extends BaseValidator
{ {
const JSON = 'json'; const JSON = 'json';
const FLOAT = 'float'; const FLOAT = 'float';
const ARRAY = 'array'; const ARRAY = 'array';
const STRING = 'string'; const STRING = 'string';
const INTEGER = 'integer'; const INTEGER = 'integer';
const SERIALIZE = 'serialize'; const SERIALIZE = 'serialize';
private ?int $min = null; private ?int $min = null;
private ?int $max = null; private ?int $max = null;
/** @var array */ /** @var array */
public array $types = [ public array $types = [
self::JSON => 'json', self::JSON => 'json',
self::FLOAT => 'float', self::FLOAT => 'float',
self::ARRAY => 'array', self::ARRAY => 'array',
self::STRING => 'string', self::STRING => 'string',
self::INTEGER => 'integer', self::INTEGER => 'integer',
self::SERIALIZE => 'serialize', self::SERIALIZE => 'serialize',
]; ];
/** @var string */ /** @var string */
public string $method; public string $method;
/** /**
* @return bool * @return bool
*/ */
public function trigger(): bool public function trigger(): bool
{ {
if (!in_array($this->method, $this->types)) { if (!in_array($this->method, $this->types)) {
return true; return true;
} }
if (empty($this->params) || !isset($this->params[$this->field])) {
$param = $this->getParams(); return true;
if (empty($param) || !isset($param[$this->field])) { }
return true; if ($this->params[$this->field] === null) {
} return $this->addError('This ' . $this->field . ' is not an empty data.');
}
$value = $param[$this->field]; return $this->{$this->method . 'Format'}($this->params[$this->field]);
}
$method = $this->method . 'Format';
/**
if ($value === null) { * @param $value
return $this->addError('This ' . $this->field . ' is not an empty data.'); * @return bool
} */
public function jsonFormat($value): bool
return $this->{$method}($value); {
} if (!is_string($value) || is_numeric($value)) {
return $this->addError('The ' . $this->field . ' not is JSON data.');
/** }
* @param $value if (is_null(json_decode($value))) {
* @return bool return $this->addError('The ' . $this->field . ' not is JSON data.');
*/ }
public function jsonFormat($value): bool return true;
{ }
if (!is_string($value) || is_numeric($value)) {
return $this->addError('The ' . $this->field . ' not is JSON data.'); /**
} * @param $value
if (is_null(json_decode($value))) { * @return bool
return $this->addError('The ' . $this->field . ' not is JSON data.'); */
} public function serializeFormat($value): bool
return true; {
} if (!is_string($value) || is_numeric($value)) {
return $this->addError('The ' . $this->field . ' not is serialize data.');
/** }
* @param $value if (false === swoole_unserialize($value)) {
* @return bool return $this->addError('The ' . $this->field . ' not is serialize data.');
*/ }
public function serializeFormat($value): bool return true;
{ }
if (!is_string($value) || is_numeric($value)) {
return $this->addError('The ' . $this->field . ' not is serialize data.'); /**
} * @param $value
if (false === swoole_unserialize($value)) { * @return bool
return $this->addError('The ' . $this->field . ' not is serialize data.'); */
} public function arrayFormat($value): bool
return true; {
} if (!is_array($value)) {
return $this->addError('The ' . $this->field . ' not is array data.');
/** }
* @param $value return true;
* @return bool }
*/
public function arrayFormat($value): bool /**
{ * @param $value
if (!is_array($value)) { * @return bool
return $this->addError('The ' . $this->field . ' not is array data.'); */
} public function stringFormat($value): bool
return true; {
} if (is_array($value) || is_object($value) || is_bool($value)) {
return $this->addError('The ' . $this->field . ' not is string data.');
/** }
* @param $value return true;
* @return bool }
*/
public function stringFormat($value): bool /**
{ * @param $value
if (is_array($value) || is_object($value) || is_bool($value)) { * @return bool
return $this->addError('The ' . $this->field . ' not is string data.'); */
} public function integerFormat($value): bool
return true; {
} if (!is_numeric($value)) {
return $this->addError('The ' . $this->field . ' not is number data.');
/** }
* @param $value if ((int)$value != $value) {
* @return bool return $this->addError('The ' . $this->field . ' not is number data.');
*/ }
public function integerFormat($value): bool
{ return true;
if (!is_numeric($value)) { }
return $this->addError('The ' . $this->field . ' not is number data.');
} /**
if ((int)$value != $value) { * @param $value
return $this->addError('The ' . $this->field . ' not is number data.'); * @return bool
} */
public function floatFormat($value): bool
return true; {
} $trim = (float)$value;
if ($trim != $value || !is_float($trim)) {
/** return $this->addError('The ' . $this->field . ' not is float data.');
* @param $value }
* @return bool return true;
*/ }
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;
}
}
+41 -43
View File
@@ -1,43 +1,41 @@
<?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 class UniqueValidator extends BaseValidator
{ {
/** /**
* @return bool * @return bool
* @throws * @throws
* 检查是否存在 * 检查是否存在
*/ */
public function trigger(): bool public function trigger(): bool
{ {
$param = $this->getParams(); $param = $this->getParams();
if (empty($param) || !isset($param[$this->field])) { if (empty($param) || !isset($param[$this->field])) {
return TRUE; return TRUE;
} }
if (empty($this->model)) { if (empty($this->model)) {
return $this->addError('Model error.'); return $this->addError('Model error.');
} }
if (!$this->model->getIsNowExample()) {
$model = $this->model; return true;
if (!$this->model->getIsNowExample()) { }
return true; if ($this->model::query()->where([$this->field => $param[$this->field]])->exists()) {
} return $this->addError('The :attribute \'' . $param[$this->field] . '\' is exists!');
if ($model::query()->where([$this->field => $param[$this->field]])->exists()) { }
return $this->addError('The :attribute \'' . $param[$this->field] . '\' is exists!'); return $this->isFail = TRUE;
} }
return $this->isFail = TRUE;
}
}
}
+221 -223
View File
@@ -1,223 +1,221 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
namespace validator; namespace validator;
use Closure; use Closure;
use Exception; use Exception;
use Kiri\Kiri; use Kiri;
/** /**
* Class Validator * Class Validator
* @package validator * @package validator
*/ */
class Validator extends BaseValidator class Validator extends BaseValidator
{ {
/** @var BaseValidator[] */ /** @var BaseValidator[] */
private ?array $validators = []; private ?array $validators = [];
/** @var ?Validator */ /** @var ?Validator */
private static ?Validator $instance = null; private static ?Validator $instance = null;
protected array $classMap = [ protected array $classMap = [
'not empty' => [ 'not empty' => [
'class' => 'validator\EmptyValidator', 'class' => 'validator\EmptyValidator',
'method' => EmptyValidator::CAN_NOT_EMPTY, 'method' => EmptyValidator::CAN_NOT_EMPTY,
], ],
'not null' => [ 'not null' => [
'class' => 'validator\EmptyValidator', 'class' => 'validator\EmptyValidator',
'method' => EmptyValidator::CAN_NOT_NULL, 'method' => EmptyValidator::CAN_NOT_NULL,
], ],
'required' => [ 'required' => [
'class' => 'validator\RequiredValidator', 'class' => 'validator\RequiredValidator',
], ],
'enum' => [ 'enum' => [
'class' => 'validator\EnumValidator', 'class' => 'validator\EnumValidator',
], ],
'unique' => [ 'unique' => [
'class' => 'validator\UniqueValidator', 'class' => 'validator\UniqueValidator',
], ],
'datetime' => [ 'datetime' => [
'class' => 'validator\DatetimeValidator', 'class' => 'validator\DatetimeValidator',
'method' => DateTimeValidator::DATE_TIME, 'method' => DateTimeValidator::DATE_TIME,
], ],
'date' => [ 'date' => [
'class' => 'validator\DatetimeValidator', 'class' => 'validator\DatetimeValidator',
'method' => DateTimeValidator::DATE, 'method' => DateTimeValidator::DATE,
], ],
'time' => [ 'time' => [
'class' => 'validator\DatetimeValidator', 'class' => 'validator\DatetimeValidator',
'method' => DateTimeValidator::TIME, 'method' => DateTimeValidator::TIME,
], ],
'timestamp' => [ 'timestamp' => [
'class' => 'validator\DatetimeValidator', 'class' => 'validator\DatetimeValidator',
'method' => DateTimeValidator::STR_TO_TIME, 'method' => DateTimeValidator::STR_TO_TIME,
], ],
'string' => [ 'string' => [
'class' => 'validator\TypesOfValidator', 'class' => 'validator\TypesOfValidator',
'method' => TypesOfValidator::STRING, 'method' => TypesOfValidator::STRING,
], ],
'int' => [ 'int' => [
'class' => 'validator\TypesOfValidator', 'class' => 'validator\TypesOfValidator',
'method' => TypesOfValidator::INTEGER, 'method' => TypesOfValidator::INTEGER,
], ],
'min' => [ 'min' => [
'class' => IntegerValidator::class 'class' => IntegerValidator::class
], ],
'max' => [ 'max' => [
'class' => IntegerValidator::class 'class' => IntegerValidator::class
], ],
'json' => [ 'json' => [
'class' => 'validator\TypesOfValidator', 'class' => 'validator\TypesOfValidator',
'method' => TypesOfValidator::JSON, 'method' => TypesOfValidator::JSON,
], ],
'float' => [ 'float' => [
'class' => 'validator\TypesOfValidator', 'class' => 'validator\TypesOfValidator',
'method' => TypesOfValidator::FLOAT, 'method' => TypesOfValidator::FLOAT,
], ],
'array' => [ 'array' => [
'class' => 'validator\TypesOfValidator', 'class' => 'validator\TypesOfValidator',
'method' => TypesOfValidator::ARRAY, 'method' => TypesOfValidator::ARRAY,
], ],
'serialize' => [ 'serialize' => [
'class' => 'validator\TypesOfValidator', 'class' => 'validator\TypesOfValidator',
'method' => TypesOfValidator::SERIALIZE, 'method' => TypesOfValidator::SERIALIZE,
], ],
'maxLength' => [ 'maxLength' => [
'class' => 'validator\LengthValidator', 'class' => 'validator\LengthValidator',
'method' => 'max', 'method' => 'max',
], ],
'minLength' => [ 'minLength' => [
'class' => 'validator\LengthValidator', 'class' => 'validator\LengthValidator',
'method' => 'min', 'method' => 'min',
], ],
'email' => [ 'email' => [
'class' => 'validator\EmailValidator', 'class' => 'validator\EmailValidator',
'method' => 'email', 'method' => 'email',
], ],
'length' => [ 'length' => [
'class' => 'validator\LengthValidator', 'class' => 'validator\LengthValidator',
'method' => 'default', 'method' => 'default',
], ],
'round' => [ 'round' => [
'class' => 'validator\RoundValidator', 'class' => 'validator\RoundValidator',
], ],
]; ];
/** /**
* @return Validator|null * @return Validator|null
*/ */
public static function getInstance(): ?Validator public static function getInstance(): ?Validator
{ {
if (static::$instance == null) { if (static::$instance == null) {
static::$instance = new Validator(); static::$instance = new Validator();
} }
return static::$instance; return static::$instance;
} }
/** /**
* @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();
foreach ($field as $val) { foreach ($field as $val) {
$this->createRule($val, $rules, $model, $param); $this->createRule($val, $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) public function createRule($field, $rule, $model, $param)
{ {
$define = ['field' => $field]; $define = ['field' => $field];
$is_model = is_null($model); $is_model = is_null($model);
foreach ($rule as $key => $val) { foreach ($rule as $key => $val) {
if (!$is_model) { if (!$is_model) {
if (is_string($val) && method_exists($model, $val)) { if (is_string($val) && method_exists($model, $val)) {
$this->validators[] = [$model, $val]; $this->validators[] = [$model, $val];
continue; continue;
} }
} }
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])) {
continue; continue;
} }
$constr = array_merge($this->classMap[$type], $define, [ $this->validators[] = array_merge($this->classMap[$type], $define, [
'params' => $param, 'params' => $param,
'model' => $model 'model' => $model
]); ]);
$this->validators[] = $constr; }
} }
}
/**
/** * @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($validator->getError());
$this->addError($validator->getError()); }
} break;
break; }
} $this->validators = [];
$this->validators = null; return !isset($isTrue);
$this->validators = []; }
return !isset($isTrue);
} /**
* @param BaseValidator|array|Closure $val
/** * @return mixed
* @param BaseValidator|array|Closure $val * @throws Exception
* @return mixed */
* @throws Exception private function check(BaseValidator|array|Closure $val): mixed
*/ {
private function check(BaseValidator|array|Closure $val): mixed if (is_callable($val, true)) {
{ return [call_user_func($val, $this), $val];
if (is_callable($val, true)) { }
return [call_user_func($val, $this), $val];
} $class = Kiri::getDi()->get($val['class']);
unset($val['class']);
$class = Kiri::getDi()->get($val['class']);
unset($val['class']); Kiri::configure($class, $val);
Kiri::configure($class, $val); return [$class->trigger(), $class];
}
return [$class->trigger(), $class];
} }
}
+1 -1
View File
@@ -15,7 +15,7 @@
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"validator\\": "src/" "validator\\": "./"
} }
}, },
"require-dev": { "require-dev": {
-35
View File
@@ -1,35 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: whwyy
* Date: 2018/4/20 0020
* Time: 17:32
*/
declare(strict_types=1);
namespace validator;
class EmailValidator extends BaseValidator
{
/**
* @return bool
* 检查是否存在
*/
public function trigger(): bool
{
$param = $this->getParams();
if (empty($param) || !isset($param[$this->field])) {
return true;
} else {
$value = $param[$this->field];
if (preg_match('/^[a-zA-Z0-9]+([\.\_]{1,})[a-zA-Z0-9]+@[a-zA-Z]+(\.\w+)+/', $value)) {
return true;
} else {
return $this->addError('The param :attribute format error');
}
}
}
}