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