From 241665983a802d77d9cec5745c5e6331a72f96d8 Mon Sep 17 00:00:00 2001 From: Tinywan <756684177@qq.com> Date: Sat, 19 Feb 2022 22:33:52 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0validate()=E5=8A=A9=E6=89=8B?= =?UTF-8?q?=E5=87=BD=E6=95=B0=EF=BC=88=E6=8E=A8=E8=8D=90=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 15 ++++++++++++++- src/helper.php | 28 ++++++++++++++-------------- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 454cc76..1f3c4e8 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ composer require tinywan/validate ``` -## 用法 +## 基础用法 ~~~php 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)章节 diff --git a/src/helper.php b/src/helper.php index 7e077d9..3004192 100644 --- a/src/helper.php +++ b/src/helper.php @@ -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); } } \ No newline at end of file