| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- <?php
- declare(strict_types=1);
- namespace app\admin\validate;
- use think\Validate;
- class BaseValidate extends Validate
- {
- public $method = 'GET';
- /**
- * @notes 设置请求方式
- */
- public function post()
- {
- if (!$this->request->isPost()) {
- throw new \think\exception\ValidateException('请求方式错误,请使用post请求方式');
- }
- $this->method = 'POST';
- return $this;
- }
- /**
- * @notes 设置请求方式
- */
- public function get()
- {
- if (!$this->request->isGet()) {
- throw new \think\exception\ValidateException('请求方式错误,请使用get请求方式');
- }
- return $this;
- }
- /**
- * @notes 切面验证接收到的参数
- * @param null $scene 场景验证
- * @param array $validateData 验证参数,可追加和覆盖掉接收的参数
- * @return array
- */
- public function goCheck($scene = null, array $validateData = []): array
- {
- //接收参数
- if ($this->method == 'GET') {
- $params = request()->get();
- } else {
- $params = request()->post();
- }
- //合并验证参数
- $params = array_merge($params, $validateData);
- //场景
- if ($scene) {
- $validateInstance = $this->scene($scene);
- $result = $validateInstance->check($params);
-
- // 获取场景中定义的only字段
- $onlyFields = property_exists($validateInstance, 'only') ? $validateInstance->only : [];
- } else {
- $result = $this->check($params);
- $onlyFields = [];
- }
- if (!$result) {
- $exception = is_array($this->error) ? implode(';', $this->error) : $this->error;
- throw new \think\exception\ValidateException($exception);
- }
-
- // 应用only字段过滤参数
- if (!empty($onlyFields)) {
- $filteredParams = [];
- foreach ($onlyFields as $field) {
- if (isset($params[$field])) {
- $filteredParams[$field] = $params[$field];
- }
- }
- return $filteredParams;
- }
-
- // 3.成功返回数据
- return $params;
- }
- }
|