BaseController.php 12 KB

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