BaseController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Leo
  5. * Date: 2017/9/3
  6. * Time: 下午3:05
  7. */
  8. namespace frontendApi\modules\v1\controllers;
  9. use common\components\ActiveRecord;
  10. use common\helpers\Date;
  11. use common\helpers\Form;
  12. use common\libs\IpFilter;
  13. use frontendApi\modules\v1\models\User;
  14. use Yii;
  15. use yii\db\Exception;
  16. use yii\web\ForbiddenHttpException;
  17. use yii\web\HttpException;
  18. class BaseController extends \yii\rest\ActiveController {
  19. /**
  20. * 不让控制器直接选择model类直接返回数据
  21. * @return array
  22. */
  23. public function actions() {
  24. return [];
  25. }
  26. /**
  27. * @throws ForbiddenHttpException
  28. */
  29. protected function forbiddenQuicklyUser() {
  30. $isQuickly = User::isQuicklyLogin();
  31. $requestMethod = Yii::$app->request->getMethod();
  32. if ($isQuickly == 1 && strtoupper($requestMethod) != 'GET') {
  33. throw new ForbiddenHttpException('快速登录的会员无法进行任何操作!');
  34. }
  35. }
  36. /**
  37. * @param $action
  38. * @return bool
  39. * @throws ForbiddenHttpException
  40. * @throws \yii\web\BadRequestHttpException
  41. */
  42. public function beforeAction($action) {
  43. $this->forbiddenQuicklyUser();
  44. $request = Yii::$app->request;
  45. if (!in_array($request->getUrl(), ['/v1/oauth/login', '/v1/oauth/is-login-verify', '/v1/site/days-diff'])) {
  46. (new IpFilter())->frontApiCheck();
  47. }
  48. // 增加的判断用户登录后未操作后的超时 和 快速登录的逻辑
  49. $isQuickly = User::isQuicklyLogin();
  50. if ($isQuickly != 1 && Yii::$app->getUser()->getUserInfo()){
  51. $userId = Yii::$app->getUser()->getUserInfo()['id'];
  52. $redisKey = 'user:timeOut';
  53. $lastTime = '';
  54. if (!Yii::$app->tokenRedis->hget($redisKey, $userId)) {
  55. $lastTime = time();
  56. }else{
  57. $lastTime = Yii::$app->tokenRedis->hget($redisKey, $userId);
  58. }
  59. $currentTime = time();
  60. $timeOut = Yii::$app->params['operationTimeOut'];
  61. if ($currentTime - $lastTime > $timeOut) {
  62. return self::notice('Connection not operated for too long', 402);
  63. } else {
  64. Yii::$app->tokenRedis->hset($redisKey, $userId, time());
  65. }
  66. }
  67. return parent::beforeAction($action);
  68. }
  69. /**
  70. * 返回结果集
  71. * @param $dataOrErrorMessage
  72. * @param int $code
  73. * @return mixed
  74. * @throws HttpException
  75. */
  76. public static function notice($dataOrErrorMessage, $code = 0) {
  77. if ($code === 0) {
  78. return $dataOrErrorMessage;
  79. } else {
  80. throw new HttpException($code, $dataOrErrorMessage, $code);
  81. }
  82. }
  83. /**
  84. * 编辑方法
  85. * @param $formModelClass
  86. * @param $successMsg
  87. * @param string|null $scenario
  88. * @param array|null $methodAndParam
  89. * [
  90. * 'edit', // form 调用对象的方法名
  91. * 'param1', // form 调用对象的方法的第一个参数
  92. * 'param2', // form 调用对象的方法的第二个参数
  93. * 'param3', // form 调用对象的方法的第三个参数
  94. * ]
  95. * @param callable|null $beforeFun
  96. * @param callable|null $afterFun
  97. * @return mixed
  98. * @throws HttpException
  99. */
  100. public static function edit($formModelClass, $successMsg, string $scenario = null, array $methodAndParam = null, callable $beforeFun = null, callable $afterFun = null) {
  101. $id = Yii::$app->request->get('id', 0);
  102. $formModel = new $formModelClass();
  103. $formModel->scenario = 'add';
  104. if ($id) {
  105. $formModel->scenario = 'edit';
  106. $formModel->id = $id;
  107. }
  108. if ($scenario !== null) {
  109. $formModel->scenario = $scenario;
  110. }
  111. if ($beforeFun) $beforeFun($formModel);
  112. if ($methodAndParam === null) {
  113. $method = 'edit';
  114. $param = [];
  115. } else {
  116. $method = $methodAndParam[0];
  117. $param = $methodAndParam;
  118. unset($param[0]);
  119. }
  120. if ($formModel->load(Yii::$app->request->post(), '') && $result = call_user_func_array([&$formModel, $method], $param)) {
  121. if ($afterFun) $afterFun($formModel, $result);
  122. return static::notice($successMsg);
  123. } else {
  124. return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 422);
  125. }
  126. }
  127. /**
  128. * 删除方法
  129. * @param $modelClass
  130. * @param callable|null $beforeFun
  131. * @param callable|null $afterFun
  132. * @param bool $isDelData
  133. * @return mixed
  134. * @throws Exception
  135. * @throws HttpException
  136. */
  137. public static function delete($modelClass, callable $beforeFun = null, callable $afterFun = null, $isDelData = true) {
  138. $selected = \Yii::$app->request->get('selected');
  139. if (!$selected) {
  140. $selected = \Yii::$app->request->post('selected');
  141. }
  142. if (!$selected) {
  143. return self::notice('必须选择一条删除数据', 500);
  144. }
  145. // 是否存在 DONT_DEL 字段
  146. if (ActiveRecord::isExistsField($modelClass, 'DONT_DEL')) {
  147. $isDontDelField = true;
  148. } else {
  149. $isDontDelField = false;
  150. }
  151. if (is_array($selected)) {
  152. if ($isDontDelField) {
  153. $condition = ['AND', ['IN', 'ID', $selected], ['<>', 'DONT_DEL', 1]];
  154. } else {
  155. $condition = ['AND', ['IN', 'ID', $selected]];
  156. }
  157. // $condition = 'ID IN ('.implode(',', $selected).') AND DONT_DEL<>1';
  158. $params = [];
  159. } else {
  160. if ($isDontDelField) {
  161. $condition = 'ID=:ID AND DONT_DEL<>1';
  162. } else {
  163. $condition = 'ID=:ID';
  164. }
  165. //$condition = ['AND', ['ID'=>$selected], ['<>', 'DONT_DEL', 1]];
  166. $params = [':ID' => $selected];
  167. }
  168. $transaction = \Yii::$app->db->beginTransaction();
  169. try {
  170. if (!is_array($selected)) {
  171. $selected = [$selected];
  172. }
  173. if ($beforeFun) $beforeFun($selected);
  174. if ($isDelData) {
  175. // 真实删除数据
  176. if (!$modelClass::deleteAll($condition, $params)) {
  177. throw new Exception('删除失败');
  178. }
  179. } else {
  180. // 设置IS_DEL字段为1
  181. $modelClass::updateAll(['IS_DEL' => 1, 'DELETED_AT' => Date::nowTime()], $condition, $params);
  182. }
  183. if ($afterFun) $afterFun($selected);
  184. $transaction->commit();
  185. return self::notice('删除成功');
  186. } catch (Exception $e) {
  187. $transaction->rollBack();
  188. return self::notice($e->getMessage(), 500);
  189. }
  190. }
  191. /**
  192. * 筛选条件
  193. * @param array $tableParams
  194. * [
  195. * '筛选提交参数名' => '表名.字段名',
  196. * 'userIds' => 'USER_INFO.USER_ID',
  197. * 'userName' => 'USER_INFO.USER_NAME',
  198. * ]
  199. *
  200. * get提交的值
  201. * [
  202. * 'userIds' => 'in,asdsa,asdsads',
  203. * 'userName' => 'like,test',
  204. * 'createdAt' => '>=,2018-11-26,date'
  205. * ]
  206. * @return array
  207. */
  208. public function filterCondition(array $tableParams = []) {
  209. $allGet = Yii::$app->request->get();
  210. $condition = '';
  211. $params = [];
  212. foreach ($tableParams as $getParam => $tableField) {
  213. if (isset($allGet[$getParam]) && $allGet[$getParam]) {
  214. $getValue = trim($allGet[$getParam], ", \t\n\r\0\x0B");
  215. $bindParam = strtoupper($getParam);
  216. if (strpos($getValue, ',') > 0) {
  217. $getValueArr = explode(',', $getValue);
  218. $getSymbol = strtoupper($getValueArr[0]);
  219. if ($getSymbol == 'IN') {
  220. $bindValueArr = $getValueArr;
  221. unset($bindValueArr[0]);
  222. $bindValue = implode("','", $bindValueArr);
  223. $bindValue = "'$bindValue'";
  224. } else {
  225. $bindValue = $getValueArr[1];
  226. if (count($getValueArr) == 3) {
  227. if ($getValueArr[2] == 'date') {
  228. $bindValue = strtotime($bindValue);
  229. }
  230. }
  231. }
  232. } else {
  233. $getSymbol = '=';
  234. $bindValue = $getValue;
  235. }
  236. if ($getSymbol == 'LIKE') {
  237. $condition .= ' AND INSTR(' . $tableField . ',:' . $bindParam . ')>0';
  238. } elseif ($getSymbol == 'IN') {
  239. $condition .= ' AND ' . $tableField . ' IN (' . $bindValue . ')';
  240. } else {
  241. $condition .= ' AND ' . $tableField . $getSymbol . ':' . $bindParam;
  242. }
  243. if ($getSymbol != 'IN') {
  244. $params[':' . $bindParam] = $bindValue;
  245. }
  246. }
  247. }
  248. return [
  249. 'condition' => $condition,
  250. 'params' => $params,
  251. 'request' => $allGet,
  252. ];
  253. }
  254. /**
  255. * 筛选条件
  256. * @param string $tableName
  257. * @param array $otherParams
  258. * [
  259. * '筛选提交参数名' => '表名.字段名',
  260. * 'userName' => 'USER_INFO.USER_NAME',
  261. * ]
  262. * 或者
  263. * [
  264. * '筛选提交参数名' => ['表名.字段名', '符号'],
  265. * 'userName' => ['USER_INFO.USER_NAME', '<'],
  266. * ]
  267. * @return array
  268. */
  269. public function filterConditionBak($tableName = '', array $otherParams = []) {
  270. $dateRange = Yii::$app->request->get('dateRange', '');
  271. $condition = '';
  272. $params = [];
  273. if ($tableName) {
  274. $tableName = $tableName . '.';
  275. }
  276. if ($dateRange) {
  277. $condition .= " AND {$tableName}CREATED_AT>:CREATED_START AND {$tableName}CREATED_AT<:CREATED_END";
  278. $params[':CREATED_START'] = Date::utcToTime($dateRange[0]);
  279. $params[':CREATED_END'] = Date::utcToTime($dateRange[1]);
  280. }
  281. $requestParams = [];
  282. foreach ($otherParams as $getParam => $field) {
  283. $getValue = Yii::$app->request->get($getParam, '');
  284. $requestParams[$getParam] = $getValue;
  285. if ($getValue === 'all') $getValue = '';
  286. if ($getValue !== '') {
  287. if (is_string($field)) {
  288. $condition .= " AND $field=:" . strtoupper($getParam);
  289. $params[':' . strtoupper($getParam)] = $getValue;
  290. } elseif (is_array($field)) {
  291. if (count($field) == 1) {
  292. $condition .= " AND {$field[0]}=:" . strtoupper($getParam);
  293. $params[':' . strtoupper($getParam)] = $getValue;
  294. } elseif (count($field) == 2) {
  295. if (strtolower($field[1]) == 'in') {
  296. $getValue = Tool::filterSpecialChar($getValue);
  297. if ($getValue) {
  298. $getValue = explode(',', $getValue);
  299. $getValue = implode("','", $getValue);
  300. $getValue = "'$getValue'";
  301. $condition .= " AND {$field[0]} IN ({$getValue})";
  302. }
  303. } else {
  304. $condition .= " AND {$field[0]}{$field[1]}:" . strtoupper($getParam);
  305. $params[':' . strtoupper($getParam)] = $getValue;
  306. }
  307. }
  308. }
  309. }
  310. }
  311. // 请求的参数也一并返回
  312. $request = array_merge([
  313. 'dateRange' => $dateRange,
  314. ], $requestParams);
  315. return [
  316. 'condition' => $condition,
  317. 'params' => $params,
  318. 'request' => $request,
  319. ];
  320. }
  321. }