BaseController.php 14 KB

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