BaseController.php 12 KB

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