BaseController.php 16 KB

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