BaseController.php 12 KB

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