RestBaseController.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +---------------------------------------------------------------------
  9. // | Author: Dean <zxxjjforever@163.com>
  10. // +----------------------------------------------------------------------
  11. namespace cmf\controller;
  12. use think\exception\HttpResponseException;
  13. use think\exception\ValidateException;
  14. use think\Request;
  15. use think\Config;
  16. use think\Response;
  17. use think\Loader;
  18. use think\Db;
  19. class RestBaseController
  20. {
  21. //token
  22. protected $token = '';
  23. //设备类型
  24. protected $deviceType = '';
  25. //用户 id
  26. protected $userId = 0;
  27. //用户
  28. protected $user;
  29. //用户类型
  30. protected $userType;
  31. protected $allowedDeviceTypes = ['mobile', 'android', 'iphone', 'ipad', 'web', 'pc', 'mac', 'wxapp'];
  32. /**
  33. * @var \think\Request Request实例
  34. */
  35. protected $request;
  36. // 验证失败是否抛出异常
  37. protected $failException = false;
  38. // 是否批量验证
  39. protected $batchValidate = false;
  40. /**
  41. * 前置操作方法列表
  42. * @var array $beforeActionList
  43. * @access protected
  44. */
  45. protected $beforeActionList = [];
  46. /**
  47. * 架构函数
  48. * @param Request $request Request对象
  49. * @access public
  50. */
  51. public function __construct(Request $request = null)
  52. {
  53. if (is_null($request)) {
  54. $request = Request::instance();
  55. }
  56. Request::instance()->root(cmf_get_root() . '/');
  57. $this->request = $request;
  58. // 用户验证初始化
  59. $this->_initUser();
  60. // 控制器初始化
  61. $this->_initialize();
  62. // 前置操作方法
  63. if ($this->beforeActionList) {
  64. foreach ($this->beforeActionList as $method => $options) {
  65. is_numeric($method) ?
  66. $this->beforeAction($options) :
  67. $this->beforeAction($method, $options);
  68. }
  69. }
  70. }
  71. // 初始化
  72. protected function _initialize()
  73. {
  74. }
  75. private function _initUser()
  76. {
  77. $token = $this->request->header('XX-Token');
  78. $deviceType = $this->request->header('XX-Device-Type');
  79. if (empty($token)) {
  80. return;
  81. }
  82. if (empty($deviceType)) {
  83. return;
  84. }
  85. if (!in_array($deviceType, $this->allowedDeviceTypes)) {
  86. return;
  87. }
  88. $this->token = $token;
  89. $this->deviceType = $deviceType;
  90. $user = Db::name('user_token')
  91. ->alias('a')
  92. ->field('b.*')
  93. ->where(['token' => $token, 'device_type' => $deviceType])
  94. ->join('__USER__ b', 'a.user_id = b.id')
  95. ->find();
  96. if (!empty($user)) {
  97. $this->user = $user;
  98. $this->userId = $user['id'];
  99. $this->userType = $user['user_type'];
  100. }
  101. }
  102. /**
  103. * 前置操作
  104. * @access protected
  105. * @param string $method 前置操作方法名
  106. * @param array $options 调用参数 ['only'=>[...]] 或者['except'=>[...]]
  107. */
  108. protected function beforeAction($method, $options = [])
  109. {
  110. if (isset($options['only'])) {
  111. if (is_string($options['only'])) {
  112. $options['only'] = explode(',', $options['only']);
  113. }
  114. if (!in_array($this->request->action(), $options['only'])) {
  115. return;
  116. }
  117. } elseif (isset($options['except'])) {
  118. if (is_string($options['except'])) {
  119. $options['except'] = explode(',', $options['except']);
  120. }
  121. if (in_array($this->request->action(), $options['except'])) {
  122. return;
  123. }
  124. }
  125. call_user_func([$this, $method]);
  126. }
  127. /**
  128. * 设置验证失败后是否抛出异常
  129. * @access protected
  130. * @param bool $fail 是否抛出异常
  131. * @return $this
  132. */
  133. protected function validateFailException($fail = true)
  134. {
  135. $this->failException = $fail;
  136. return $this;
  137. }
  138. /**
  139. * 验证数据
  140. * @access protected
  141. * @param array $data 数据
  142. * @param string|array $validate 验证器名或者验证规则数组
  143. * @param array $message 提示信息
  144. * @param bool $batch 是否批量验证
  145. * @param mixed $callback 回调方法(闭包)
  146. * @return array|string|true
  147. * @throws ValidateException
  148. */
  149. protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
  150. {
  151. if (is_array($validate)) {
  152. $v = Loader::validate();
  153. $v->rule($validate);
  154. } else {
  155. if (strpos($validate, '.')) {
  156. // 支持场景
  157. list($validate, $scene) = explode('.', $validate);
  158. }
  159. $v = Loader::validate($validate);
  160. if (!empty($scene)) {
  161. $v->scene($scene);
  162. }
  163. }
  164. // 是否批量验证
  165. if ($batch || $this->batchValidate) {
  166. $v->batch(true);
  167. }
  168. if (is_array($message)) {
  169. $v->message($message);
  170. }
  171. if ($callback && is_callable($callback)) {
  172. call_user_func_array($callback, [$v, &$data]);
  173. }
  174. if (!$v->check($data)) {
  175. if ($this->failException) {
  176. throw new ValidateException($v->getError());
  177. } else {
  178. return $v->getError();
  179. }
  180. } else {
  181. return true;
  182. }
  183. }
  184. /**
  185. * 操作成功跳转的快捷方法
  186. * @access protected
  187. * @param mixed $msg 提示信息
  188. * @param mixed $data 返回的数据
  189. * @param array $header 发送的Header信息
  190. * @return void
  191. */
  192. protected function success($msg = '', $data = '', array $header = [])
  193. {
  194. $code = 1;
  195. $result = [
  196. 'code' => $code,
  197. 'msg' => $msg,
  198. 'data' => $data,
  199. ];
  200. $type = $this->getResponseType();
  201. $header['Access-Control-Allow-Origin'] = '*';
  202. $header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type,XX-Device-Type,XX-Token';
  203. $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
  204. $response = Response::create($result, $type)->header($header);
  205. throw new HttpResponseException($response);
  206. }
  207. /**
  208. * 操作错误跳转的快捷方法
  209. * @access protected
  210. * @param mixed $msg 提示信息,若要指定错误码,可以传数组,格式为['code'=>您的错误码,'msg'=>'您的错误消息']
  211. * @param mixed $data 返回的数据
  212. * @param array $header 发送的Header信息
  213. * @return void
  214. */
  215. protected function error($msg = '', $data = '', array $header = [])
  216. {
  217. $code = 0;
  218. if (is_array($msg)) {
  219. $code = $msg['code'];
  220. $msg = $msg['msg'];
  221. }
  222. $result = [
  223. 'code' => $code,
  224. 'msg' => $msg,
  225. 'data' => $data,
  226. ];
  227. $type = $this->getResponseType();
  228. $header['Access-Control-Allow-Origin'] = '*';
  229. $header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type,XX-Device-Type,XX-Token';
  230. $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
  231. $response = Response::create($result, $type)->header($header);
  232. throw new HttpResponseException($response);
  233. }
  234. /**
  235. * 获取当前的response 输出类型
  236. * @access protected
  237. * @return string
  238. */
  239. protected function getResponseType()
  240. {
  241. return Config::get('default_return_type');
  242. }
  243. /**
  244. * 获取当前登录用户的id
  245. * @return int
  246. */
  247. public function getUserId()
  248. {
  249. if (empty($this->userId)) {
  250. $this->error(['code' => 10001, 'msg' => '用户未登录']);
  251. }
  252. return $this->userId;
  253. }
  254. }