RestBaseController.php 8.3 KB

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