Skip to content

Commit

Permalink
增加validate()助手函数(推荐)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tinywan committed Feb 19, 2022
1 parent ad63399 commit 2416659
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 15 deletions.
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
composer require tinywan/validate
```

## 用法
## 基础用法

~~~php
<?php
Expand Down Expand Up @@ -59,5 +59,18 @@ if (!$validate->check($data)) {
}
~~~

## 助手函数(推荐)

验证器调用代码如下:
```php
$data = [
'name' => 'Tinywan',
'age' => 24,
'email' => 'Tinywan@163.com'
];
validate($data, \app\index\validate\UserValidate::class . '.issue');
```
> 验证错误会自动抛出异常
更多用法可以参考6.0完全开发手册的[验证](https://www.kancloud.cn/manual/thinkphp6_0/1037623)章节

28 changes: 14 additions & 14 deletions src/helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,38 @@
declare (strict_types = 1);

namespace Tinywan\Validate;
use function is_array;
use function strpos;
use function explode;

if (!function_exists('validate')) {
/**
* 生成验证对象
* @param string|array $validate 验证器类名或者验证规则数组
* @param array $message 错误提示信息
* @param bool $batch 是否批量验证
* @param bool $failException 是否抛出异常
* @param array $data 数据
* @param string|array $validate 验证器类名或者验证规则数组
* @param array $message 错误提示信息
* @param bool $batch 是否批量验证
* @param bool $failException 是否抛出异常
* @return Validate
*/
function validate($validate = '', array $message = [], bool $batch = false, bool $failException = true): Validate
function validate(array $data, $validate = '', array $message = [], bool $batch = false, bool $failException = true): Validate
{
if (is_array($validate) || '' === $validate) {
if (is_array($validate)) {
$v = new Validate();
if (is_array($validate)) {
$v->rule($validate);
}
$v->rule($validate);
} else {
if (strpos($validate, '.')) {
// 支持场景
[$validate, $scene] = explode('.', $validate);
}

$class = false !== strpos($validate, '\\') ? $validate : $validate;

$v = new $class();

if (!empty($scene)) {
$v->scene($scene);
}
}

return $v->message($message)->batch($batch)->failException($failException);
$v->message($message);
$v->batch($batch);
return $v->failException($failException)->check($data);
}
}

0 comments on commit 2416659

Please sign in to comment.