BaseController.php 12 KB

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