BaseValidate.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\admin\validate;
  4. use think\Validate;
  5. class BaseValidate extends Validate
  6. {
  7. public $method = 'GET';
  8. /**
  9. * @notes 设置请求方式
  10. */
  11. public function post()
  12. {
  13. if (!$this->request->isPost()) {
  14. throw new \think\exception\ValidateException('请求方式错误,请使用post请求方式');
  15. }
  16. $this->method = 'POST';
  17. return $this;
  18. }
  19. /**
  20. * @notes 设置请求方式
  21. */
  22. public function get()
  23. {
  24. if (!$this->request->isGet()) {
  25. throw new \think\exception\ValidateException('请求方式错误,请使用get请求方式');
  26. }
  27. return $this;
  28. }
  29. /**
  30. * @notes 切面验证接收到的参数
  31. * @param null $scene 场景验证
  32. * @param array $validateData 验证参数,可追加和覆盖掉接收的参数
  33. * @return array
  34. */
  35. public function goCheck($scene = null, array $validateData = []): array
  36. {
  37. //接收参数
  38. if ($this->method == 'GET') {
  39. $params = request()->get();
  40. } else {
  41. $params = request()->post();
  42. }
  43. //合并验证参数
  44. $params = array_merge($params, $validateData);
  45. //场景
  46. if ($scene) {
  47. $result = $this->scene($scene)->check($params);
  48. } else {
  49. $result = $this->check($params);
  50. }
  51. if (!$result) {
  52. $exception = is_array($this->error) ? implode(';', $this->error) : $this->error;
  53. throw new \think\exception\ValidateException($exception);
  54. }
  55. // 3.成功返回数据
  56. return $params;
  57. }
  58. }