BaseValidate.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. $validateInstance = $this->scene($scene);
  48. $result = $validateInstance->check($params);
  49. // 获取场景中定义的only字段
  50. $onlyFields = property_exists($validateInstance, 'only') ? $validateInstance->only : [];
  51. } else {
  52. $result = $this->check($params);
  53. $onlyFields = [];
  54. }
  55. if (!$result) {
  56. $exception = is_array($this->error) ? implode(';', $this->error) : $this->error;
  57. throw new \think\exception\ValidateException($exception);
  58. }
  59. // 应用only字段过滤参数
  60. if (!empty($onlyFields)) {
  61. $filteredParams = [];
  62. foreach ($onlyFields as $field) {
  63. if (isset($params[$field])) {
  64. $filteredParams[$field] = $params[$field];
  65. }
  66. }
  67. return $filteredParams;
  68. }
  69. // 3.成功返回数据
  70. return $params;
  71. }
  72. }