BaseController.php 13 KB

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