BaseController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Leo
  5. * Date: 2017/9/3
  6. * Time: 下午3:05
  7. */
  8. namespace backendApi\modules\v1\controllers;
  9. use common\helpers\Date;
  10. use common\helpers\Tool;
  11. use common\models\UserInfo;
  12. use common\models\UserSystem;
  13. use \Yii;
  14. use common\components\ActiveRecord;
  15. use common\helpers\Form;
  16. use yii\db\Exception;
  17. use yii\web\HttpException;
  18. class BaseController extends \yii\rest\ActiveController {
  19. /**
  20. * 不让控制器直接选择model类直接返回数据
  21. * @return array
  22. */
  23. public function actions() {
  24. return [];
  25. }
  26. /**
  27. * 校验管理员权限
  28. * @param $action
  29. * @return bool|mixed
  30. * @throws HttpException
  31. * @throws \yii\web\BadRequestHttpException
  32. */
  33. public function beforeAction($action) {
  34. // 动态返回语言:zh:zh-CN | en:en-US
  35. if (!Yii::$app->request->isOptions) {
  36. $language = Yii::$app->request->headers->get('language') ?? 'en';
  37. Yii::$app->language = $language == 'zh' ? 'zh-CN' : 'en-US';
  38. Yii::$app->sourceLanguage = $language == 'zh' ? 'en-US' : 'zh-CN';
  39. }
  40. $parentBeforeAction = parent::beforeAction($action);
  41. // 增加的判断用户登录后未操作后的超时
  42. if (Yii::$app->getUser()->getUserInfo()){
  43. $adminId = Yii::$app->getUser()->getUserInfo()['id'];
  44. $redisKey = 'admin:timeOut';
  45. $lastTime = '';
  46. if (!Yii::$app->tokenRedis->hget($redisKey, $adminId)) {
  47. $lastTime = time();
  48. }else{
  49. $lastTime = Yii::$app->tokenRedis->hget($redisKey, $adminId);
  50. }
  51. $currentTime = time();
  52. $timeOut = Yii::$app->params['operationTimeOut'];
  53. if ($currentTime - $lastTime > $timeOut) {
  54. return self::notice('Connection not operated for too long', 402);
  55. } else {
  56. Yii::$app->tokenRedis->hset($redisKey, $adminId, time());
  57. }
  58. }
  59. // 校验用户权限
  60. if (!Yii::$app->user->validateAdminAction($this->id, $this->action->id)) {
  61. return self::notice('Insufficient user permissions', 403);
  62. }
  63. return $parentBeforeAction;
  64. }
  65. /**
  66. * 返回结果集
  67. * @param $dataOrErrorMessage
  68. * @param int $code
  69. * @return mixed
  70. * @throws HttpException
  71. */
  72. public static function notice($dataOrErrorMessage, $code = 0) {
  73. if ($code === 0) {
  74. return $dataOrErrorMessage;
  75. } else {
  76. throw new HttpException($code, $dataOrErrorMessage, $code);
  77. }
  78. }
  79. /**
  80. * 编辑方法
  81. * @param $formModelClass
  82. * @param $successMsg
  83. * @param string|null $scenario
  84. * @param array|null $methodAndParam
  85. * [
  86. * 'edit', // form 调用对象的方法名
  87. * 'param1', // form 调用对象的方法的第一个参数
  88. * 'param2', // form 调用对象的方法的第二个参数
  89. * 'param3', // form 调用对象的方法的第三个参数
  90. * ]
  91. * @param callable|null $beforeFun
  92. * @param callable|null $afterFun
  93. * @return mixed
  94. * @throws HttpException
  95. */
  96. public static function edit($formModelClass, $successMsg, string $scenario = null, array $methodAndParam = null, callable $beforeFun = null, callable $afterFun = null) {
  97. $id = Yii::$app->request->get('id', 0);
  98. $formModel = new $formModelClass();
  99. $formModel->scenario = 'add';
  100. if ($id) {
  101. $formModel->scenario = 'edit';
  102. $formModel->id = $id;
  103. }
  104. if ($scenario !== null) {
  105. $formModel->scenario = $scenario;
  106. }
  107. if ($beforeFun) $beforeFun($formModel);
  108. if ($methodAndParam === null) {
  109. $method = 'edit';
  110. $param = [];
  111. } else {
  112. $method = $methodAndParam[0];
  113. $param = $methodAndParam;
  114. unset($param[0]);
  115. }
  116. if ($formModel->load(Yii::$app->request->post(), '') && $result = call_user_func_array([&$formModel, $method], $param)) {
  117. if ($afterFun) $afterFun($formModel, $result);
  118. return static::notice($successMsg);
  119. } else {
  120. return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 422);
  121. }
  122. }
  123. /**
  124. * 隐藏方法
  125. *
  126. */
  127. public static function hide($modelClass, $statusTo, callable $beforeFun = null, callable $afterFun = null) {
  128. $selected = \Yii::$app->request->get('selected');
  129. if (!$selected) {
  130. $selected = \Yii::$app->request->post('selected');
  131. }
  132. if (!$selected) {
  133. return self::notice('must select one item to hide', 500); // 必须选择一条删除数据
  134. }
  135. if (is_array($selected)) {
  136. $condition = ['AND', ['IN', 'ID', $selected]];
  137. $params = [];
  138. } else {
  139. $condition = 'ID=:ID';
  140. $params = [':ID' => $selected];
  141. }
  142. $transaction = \Yii::$app->db->beginTransaction();
  143. try {
  144. if (!is_array($selected)) {
  145. $selected = [$selected];
  146. }
  147. if ($beforeFun) $beforeFun($selected);
  148. if ($statusTo == 'hide') {
  149. $modelClass::updateAll(['STATUS' => 0], $condition, $params);
  150. $stateStr = 'hide';
  151. } else {
  152. $modelClass::updateAll(['STATUS' => 1], $condition, $params);
  153. $stateStr = 'Unhide';
  154. }
  155. if ($afterFun) $afterFun($selected);
  156. $transaction->commit();
  157. return self::notice($stateStr.' successfully'); // 隐藏/取消隐藏 成功
  158. } catch (Exception $e) {
  159. $transaction->rollBack();
  160. return self::notice($e->getMessage(), 500);
  161. }
  162. }
  163. /**
  164. * 删除方法
  165. * @param $modelClass
  166. * @param callable|null $beforeFun
  167. * @param callable|null $afterFun
  168. * @param bool $isDelData
  169. * @return mixed
  170. * @throws Exception
  171. * @throws HttpException
  172. */
  173. public static function delete($modelClass, callable $beforeFun = null, callable $afterFun = null, $isDelData = true) {
  174. $selected = \Yii::$app->request->get('selected');
  175. if (!$selected) {
  176. $selected = \Yii::$app->request->post('selected');
  177. }
  178. if (!$selected) {
  179. return self::notice('must select one item to delete', 500);// 必须选择一条删除数据
  180. }
  181. // 是否存在 DONT_DEL 字段
  182. if (ActiveRecord::isExistsField($modelClass, 'DONT_DEL')) {
  183. $isDontDelField = true;
  184. } else {
  185. $isDontDelField = false;
  186. }
  187. if (is_array($selected)) {
  188. if ($isDontDelField) {
  189. $condition = ['AND', ['IN', 'ID', $selected], ['<>', 'DONT_DEL', 1]];
  190. } else {
  191. $condition = ['AND', ['IN', 'ID', $selected]];
  192. }
  193. // $condition = 'ID IN ('.implode(',', $selected).') AND DONT_DEL<>1';
  194. $params = [];
  195. } else {
  196. if ($isDontDelField) {
  197. $condition = 'ID=:ID AND DONT_DEL<>1';
  198. } else {
  199. $condition = 'ID=:ID';
  200. }
  201. //$condition = ['AND', ['ID'=>$selected], ['<>', 'DONT_DEL', 1]];
  202. $params = [':ID' => $selected];
  203. }
  204. $transaction = \Yii::$app->db->beginTransaction();
  205. try {
  206. if (!is_array($selected)) {
  207. $selected = [$selected];
  208. }
  209. if ($beforeFun) $beforeFun($selected);
  210. if ($isDelData) {
  211. // 真实删除数据
  212. if (!$modelClass::deleteAll($condition, $params)) {
  213. throw new Exception(Yii::t('ctx', 'deleteFailed'));//删除失败
  214. }
  215. } else {
  216. // 设置IS_DEL字段为1
  217. $modelClass::updateAll(['IS_DEL' => 1, 'DELETED_AT' => Date::nowTime()], $condition, $params);
  218. }
  219. if ($afterFun) $afterFun($selected);
  220. $transaction->commit();
  221. return self::notice(Yii::t('ctx', 'deleteSuccessfully'));//删除成功
  222. } catch (Exception $e) {
  223. $transaction->rollBack();
  224. return self::notice($e->getMessage(), 500);
  225. }
  226. }
  227. /**
  228. * 筛选条件
  229. * @param array $tableParams
  230. * [
  231. * '筛选提交参数名' => '表名.字段名',
  232. * 'userIds' => 'USER_INFO.USER_ID',
  233. * 'userName' => 'USER_INFO.USER_NAME',
  234. * ]
  235. *
  236. * get提交的值
  237. * [
  238. * 'userIds' => 'in,asdsa,asdsads',
  239. * 'userName' => 'like,test',
  240. * 'createdAt' => '>=,2018-11-26,date'
  241. * ]
  242. * @return array
  243. */
  244. public function filterCondition(array $tableParams = []) {
  245. $allGet = Yii::$app->request->get();
  246. $condition = '';
  247. $params = [];
  248. foreach ($tableParams as $getParam => $tableField) {
  249. if (isset($allGet[$getParam]) && $allGet[$getParam]) {
  250. $getValue = trim($allGet[$getParam], ", \t\n\r\0\x0B");
  251. $bindParam = strtoupper($getParam);
  252. if (strpos($getValue, '|') > 0) {
  253. $condition .= ' AND (';
  254. $chidValueArr = explode('|', $getValue);
  255. foreach ($chidValueArr as $k => $value) {
  256. if ($k == 0) {
  257. $result = $this->_getConditionAndParams($value, $tableField, $bindParam . $k, '');
  258. } else {
  259. $result = $this->_getConditionAndParams($value, $tableField, $bindParam . $k, 'OR');
  260. }
  261. $condition .= $result['condition'];
  262. $params += $result['params'];
  263. }
  264. $condition .= ')';
  265. } else {
  266. $result = $this->_getConditionAndParams($getValue, $tableField, $bindParam);
  267. $condition .= $result['condition'];
  268. $params += $result['params'];
  269. }
  270. }
  271. }
  272. return [
  273. 'condition' => $condition,
  274. 'params' => $params,
  275. 'request' => $allGet,
  276. ];
  277. }
  278. /**
  279. * 获取条件
  280. * @param $getValue
  281. * @param $tableField
  282. * @param $bindParam
  283. * @param string $relation
  284. * @return array
  285. */
  286. private function _getConditionAndParams($getValue, $tableField, $bindParam, $relation = 'AND') {
  287. $condition = '';
  288. $params = [];
  289. $isDate = false;
  290. $filterModel = '';
  291. if (strpos($getValue, ',') > 0) {
  292. $getValueArr = explode(',', $getValue);
  293. $getSymbol = strtoupper($getValueArr[0]);
  294. if ($getSymbol == 'IN') {
  295. $bindValueArr = $getValueArr;
  296. unset($bindValueArr[0]);
  297. $bindValue = implode("','", $bindValueArr);
  298. $bindValue = "'$bindValue'";
  299. } else {
  300. $bindValue = $getValueArr[1];
  301. $filterModel = end($getValueArr);
  302. reset($getValueArr);
  303. if($filterModel == 'date'){
  304. if( $getSymbol !== '>=' && $getSymbol !== '<=' && $getSymbol !== '>' && $getSymbol !== '<' ) {
  305. throw new \Exception(Yii::t('ctx', 'incorrectDateFormat'));//日期筛选格式不对
  306. }
  307. $bindValue = strtotime($getValueArr[1]);
  308. $isDate = true;
  309. $relation = $relation ? 'AND' : '';
  310. }
  311. elseif($filterModel == 'area'){
  312. $bindValue = array_slice($getValueArr, 1, 3);
  313. }
  314. }
  315. } else {
  316. $getSymbol = '=';
  317. $bindValue = $getValue;
  318. }
  319. if ($getSymbol == 'LIKE') {
  320. $condition .= ' ' . $relation . ' INSTR(' . $tableField . ',:' . $bindParam . ')>0';
  321. } elseif ($getSymbol == strtoupper('notLike')) {
  322. $condition .= ' ' . $relation . ' INSTR(' . $tableField . ',:' . $bindParam . ')=0';
  323. } elseif ($getSymbol == 'IN') {
  324. $condition .= ' ' . $relation . ' ' . $tableField . ' IN (' . $bindValue . ')';
  325. } else {
  326. if ($isDate && $getSymbol == '=') {
  327. $condition .= ' ' . $relation . ' ' . $tableField . '>=:' . $bindParam . 's';
  328. $condition .= ' AND ' . $tableField . '<=:' . $bindParam . 'e';
  329. }
  330. elseif($filterModel == 'area'){
  331. if($bindValue[0]){
  332. $condition .= ' AND '.$tableField['FIELD'][0].'=:'.$tableField['BIND'][0];
  333. if(isset($bindValue[1])&&$bindValue[1]&&$bindValue[1]!='area'){
  334. $condition .= ' AND '.$tableField['FIELD'][1].'=:'.$tableField['BIND'][1];
  335. if(isset($bindValue[2])&&$bindValue[2]&&$bindValue[2]!='area'){
  336. $condition .= ' AND '.$tableField['FIELD'][2].'=:'.$tableField['BIND'][2];
  337. }
  338. }
  339. }
  340. }
  341. else {
  342. if($getSymbol!=='=' && $relation=='OR'){
  343. $relation = 'AND';
  344. }
  345. $condition .= ' ' . $relation . ' ' . $tableField . $getSymbol . ':' . $bindParam;
  346. }
  347. }
  348. if ($getSymbol != 'IN') {
  349. if ($isDate && $getSymbol == '=') {
  350. $params[':' . $bindParam . 's'] = $bindValue;
  351. $params[':' . $bindParam . 'e'] = $bindValue + 86399;
  352. }
  353. if ($filterModel == 'area') {
  354. if($bindValue[0]){
  355. $params[':'.$tableField['BIND'][0]] = $bindValue[0];
  356. if(isset($bindValue[1])&&$bindValue[1]&&$bindValue[1]!='area'){
  357. $params[':'.$tableField['BIND'][1]] = $bindValue[1];
  358. if(isset($bindValue[2])&&$bindValue[2]&&$bindValue[2]!='area'){
  359. $params[':'.$tableField['BIND'][2]] = $bindValue[2];
  360. }
  361. }
  362. }
  363. }
  364. else {
  365. $params[':' . $bindParam] = $bindValue;
  366. }
  367. }
  368. return ['condition' => $condition, 'params' => $params];
  369. }
  370. /**
  371. * 筛选条件
  372. * @param string $tableName
  373. * @param array $otherParams
  374. * [
  375. * '筛选提交参数名' => '表名.字段名',
  376. * 'userName' => 'USER_INFO.USER_NAME',
  377. * ]
  378. * 或者
  379. * [
  380. * '筛选提交参数名' => ['表名.字段名', '符号'],
  381. * 'userName' => ['USER_INFO.USER_NAME', '<'],
  382. * ]
  383. * @return array
  384. */
  385. public function filterConditionBak($tableName = '', array $otherParams = []) {
  386. $dateRange = Yii::$app->request->get('dateRange', '');
  387. $condition = '';
  388. $params = [];
  389. if ($tableName) {
  390. $tableName = $tableName . '.';
  391. }
  392. if ($dateRange) {
  393. $condition .= " AND {$tableName}CREATED_AT>:CREATED_START AND {$tableName}CREATED_AT<:CREATED_END";
  394. $params[':CREATED_START'] = Date::utcToTime($dateRange[0]);
  395. $params[':CREATED_END'] = Date::utcToTime($dateRange[1]);
  396. }
  397. $requestParams = [];
  398. foreach ($otherParams as $getParam => $field) {
  399. $getValue = Yii::$app->request->get($getParam, '');
  400. $requestParams[$getParam] = $getValue;
  401. if ($getValue === 'all') $getValue = '';
  402. if ($getValue !== '') {
  403. if (is_string($field)) {
  404. $condition .= " AND $field=:" . strtoupper($getParam);
  405. $params[':' . strtoupper($getParam)] = $getValue;
  406. } elseif (is_array($field)) {
  407. if (count($field) == 1) {
  408. $condition .= " AND {$field[0]}=:" . strtoupper($getParam);
  409. $params[':' . strtoupper($getParam)] = $getValue;
  410. } elseif (count($field) == 2) {
  411. if (strtolower($field[1]) == 'in') {
  412. $getValue = Tool::filterSpecialChar($getValue);
  413. if ($getValue) {
  414. $getValue = explode(',', $getValue);
  415. $getValue = implode("','", $getValue);
  416. $getValue = "'$getValue'";
  417. $condition .= " AND {$field[0]} IN ({$getValue})";
  418. }
  419. } else {
  420. $condition .= " AND {$field[0]}{$field[1]}:" . strtoupper($getParam);
  421. $params[':' . strtoupper($getParam)] = $getValue;
  422. }
  423. }
  424. }
  425. }
  426. }
  427. // 请求的参数也一并返回
  428. $request = array_merge([
  429. 'dateRange' => $dateRange,
  430. ], $requestParams);
  431. return [
  432. 'condition' => $condition,
  433. 'params' => $params,
  434. 'request' => $request,
  435. ];
  436. }
  437. }