You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
2.6 KiB

1 year ago
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app;
  4. use think\App;
  5. use think\exception\ValidateException;
  6. use think\Validate;
  7. use think\facade\View;
  8. /**
  9. * 控制器基础类
  10. */
  11. abstract class BaseController
  12. {
  13. /**
  14. * Request实例
  15. * @var \think\Request
  16. */
  17. protected $request;
  18. /**
  19. * 应用实例
  20. * @var \think\App
  21. */
  22. protected $app;
  23. /**
  24. * 是否批量验证
  25. * @var bool
  26. */
  27. protected $batchValidate = false;
  28. /**
  29. * 控制器中间件
  30. * @var array
  31. */
  32. protected $middleware = [];
  33. protected $clientip;
  34. /**
  35. * 构造方法
  36. * @access public
  37. * @param App $app 应用对象
  38. */
  39. public function __construct(App $app)
  40. {
  41. $this->app = $app;
  42. $this->request = $this->app->request;
  43. // 控制器初始化
  44. $this->initialize();
  45. }
  46. // 初始化
  47. protected function initialize()
  48. {
  49. $this->clientip = real_ip();
  50. }
  51. /**
  52. * 验证数据
  53. * @access protected
  54. * @param array $data 数据
  55. * @param string|array $validate 验证器名或者验证规则数组
  56. * @param array $message 提示信息
  57. * @param bool $batch 是否批量验证
  58. * @return array|string|true
  59. * @throws ValidateException
  60. */
  61. protected function validate(array $data, $validate, array $message = [], bool $batch = false)
  62. {
  63. if (is_array($validate)) {
  64. $v = new Validate();
  65. $v->rule($validate);
  66. } else {
  67. if (strpos($validate, '.')) {
  68. // 支持场景
  69. [$validate, $scene] = explode('.', $validate);
  70. }
  71. $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
  72. $v = new $class();
  73. if (!empty($scene)) {
  74. $v->scene($scene);
  75. }
  76. }
  77. $v->message($message);
  78. // 是否批量验证
  79. if ($batch || $this->batchValidate) {
  80. $v->batch(true);
  81. }
  82. return $v->failException(true)->check($data);
  83. }
  84. protected function alert($code, $msg = '', $url = null, $wait = 3)
  85. {
  86. if ($url) {
  87. $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : (string)$this->app->route->buildUrl($url);
  88. }
  89. if(empty($msg)) $msg = '未知错误';
  90. View::assign([
  91. 'code' => $code,
  92. 'msg' => $msg,
  93. 'url' => $url,
  94. 'wait' => $wait,
  95. ]);
  96. return View::fetch(app()->getAppPath().'view/dispatch_jump.html');
  97. }
  98. }