BaseController.php 13 KB

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