Base.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * 公共控制器类
  4. *
  5. */
  6. namespace app\common\controller;
  7. use think\Controller;
  8. use think\exception\ValidateException;
  9. use think\Request;
  10. class Base extends Controller
  11. {
  12. /**
  13. * 初始化数据
  14. */
  15. protected function _initialize(){}
  16. /**
  17. * 重构父类的validate方法
  18. * @access protected
  19. * @param array $data 数据
  20. * @param string|array $validate 验证器名或者验证规则数组
  21. * @param array $message 提示信息
  22. * @param bool $batch 是否批量验证
  23. * @param mixed $callback 回调方法(闭包)
  24. * @return array|string|true
  25. * @throws ValidateException
  26. */
  27. public function validate($data, $validate, $message = [], $batch = false, $callback = null)
  28. {
  29. if (is_array($validate)) {
  30. $v = new \app\common\library\ValidateExtend; //调用Validate的扩展类
  31. $v->rule($validate);
  32. } else {
  33. // 支持场景
  34. if (strpos($validate, '.')) {
  35. list($validate, $scene) = explode('.', $validate);
  36. }
  37. $v = \think\Loader::validate($validate);
  38. !empty($scene) && $v->scene($scene);
  39. }
  40. // 是否批量验证
  41. if ($batch || $this->batchValidate) {
  42. $v->batch(true);
  43. }
  44. if (is_array($message)) {
  45. $v->message($message);
  46. }
  47. if ($callback && is_callable($callback)) {
  48. call_user_func_array($callback, [$v, &$data]);
  49. }
  50. if (!$v->check($data)) {
  51. if ($this->failException) {
  52. throw new ValidateException($v->getError());
  53. } else {
  54. return $v->getError();
  55. }
  56. } else {
  57. return true;
  58. }
  59. }
  60. }