BaseController.php 13 KB

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