BaseController.php 13 KB

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