BaseController.php 12 KB

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