BaseController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. $stateStr = 'hide';
  145. } else {
  146. $modelClass::updateAll(['STATUS' => 1], $condition, $params);
  147. $stateStr = 'Unhide';
  148. }
  149. if ($afterFun) $afterFun($selected);
  150. $transaction->commit();
  151. return self::notice($stateStr.' successfully'); // 隐藏/取消隐藏 成功
  152. } catch (Exception $e) {
  153. $transaction->rollBack();
  154. return self::notice($e->getMessage(), 500);
  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('must select one item to delete', 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. $condition .= ' AND (';
  248. $chidValueArr = explode('|', $getValue);
  249. foreach ($chidValueArr as $k => $value) {
  250. if ($k == 0) {
  251. $result = $this->_getConditionAndParams($value, $tableField, $bindParam . $k, '');
  252. } else {
  253. $result = $this->_getConditionAndParams($value, $tableField, $bindParam . $k, 'OR');
  254. }
  255. $condition .= $result['condition'];
  256. $params += $result['params'];
  257. }
  258. $condition .= ')';
  259. } else {
  260. $result = $this->_getConditionAndParams($getValue, $tableField, $bindParam);
  261. $condition .= $result['condition'];
  262. $params += $result['params'];
  263. }
  264. }
  265. }
  266. return [
  267. 'condition' => $condition,
  268. 'params' => $params,
  269. 'request' => $allGet,
  270. ];
  271. }
  272. /**
  273. * 获取条件
  274. * @param $getValue
  275. * @param $tableField
  276. * @param $bindParam
  277. * @param string $relation
  278. * @return array
  279. */
  280. private function _getConditionAndParams($getValue, $tableField, $bindParam, $relation = 'AND') {
  281. $condition = '';
  282. $params = [];
  283. $isDate = false;
  284. $filterModel = '';
  285. if (strpos($getValue, ',') > 0) {
  286. $getValueArr = explode(',', $getValue);
  287. $getSymbol = strtoupper($getValueArr[0]);
  288. if ($getSymbol == 'IN') {
  289. $bindValueArr = $getValueArr;
  290. unset($bindValueArr[0]);
  291. $bindValue = implode("','", $bindValueArr);
  292. $bindValue = "'$bindValue'";
  293. } else {
  294. $bindValue = $getValueArr[1];
  295. $filterModel = end($getValueArr);
  296. reset($getValueArr);
  297. if($filterModel == 'date'){
  298. if( $getSymbol !== '>=' && $getSymbol !== '<=' && $getSymbol !== '>' && $getSymbol !== '<' ) {
  299. throw new \Exception("Incorrect date format");//日期筛选格式不对
  300. }
  301. $bindValue = strtotime($getValueArr[1]);
  302. $isDate = true;
  303. $relation = $relation ? 'AND' : '';
  304. }
  305. elseif($filterModel == 'area'){
  306. $bindValue = array_slice($getValueArr, 1, 3);
  307. }
  308. }
  309. } else {
  310. $getSymbol = '=';
  311. $bindValue = $getValue;
  312. }
  313. if ($getSymbol == 'LIKE') {
  314. $condition .= ' ' . $relation . ' INSTR(' . $tableField . ',:' . $bindParam . ')>0';
  315. } elseif ($getSymbol == strtoupper('notLike')) {
  316. $condition .= ' ' . $relation . ' INSTR(' . $tableField . ',:' . $bindParam . ')=0';
  317. } elseif ($getSymbol == 'IN') {
  318. $condition .= ' ' . $relation . ' ' . $tableField . ' IN (' . $bindValue . ')';
  319. } else {
  320. if ($isDate && $getSymbol == '=') {
  321. $condition .= ' ' . $relation . ' ' . $tableField . '>=:' . $bindParam . 's';
  322. $condition .= ' AND ' . $tableField . '<=:' . $bindParam . 'e';
  323. }
  324. elseif($filterModel == 'area'){
  325. if($bindValue[0]){
  326. $condition .= ' AND '.$tableField['FIELD'][0].'=:'.$tableField['BIND'][0];
  327. if(isset($bindValue[1])&&$bindValue[1]&&$bindValue[1]!='area'){
  328. $condition .= ' AND '.$tableField['FIELD'][1].'=:'.$tableField['BIND'][1];
  329. if(isset($bindValue[2])&&$bindValue[2]&&$bindValue[2]!='area'){
  330. $condition .= ' AND '.$tableField['FIELD'][2].'=:'.$tableField['BIND'][2];
  331. }
  332. }
  333. }
  334. }
  335. else {
  336. if($getSymbol!=='=' && $relation=='OR'){
  337. $relation = 'AND';
  338. }
  339. $condition .= ' ' . $relation . ' ' . $tableField . $getSymbol . ':' . $bindParam;
  340. }
  341. }
  342. if ($getSymbol != 'IN') {
  343. if ($isDate && $getSymbol == '=') {
  344. $params[':' . $bindParam . 's'] = $bindValue;
  345. $params[':' . $bindParam . 'e'] = $bindValue + 86399;
  346. }
  347. if ($filterModel == 'area') {
  348. if($bindValue[0]){
  349. $params[':'.$tableField['BIND'][0]] = $bindValue[0];
  350. if(isset($bindValue[1])&&$bindValue[1]&&$bindValue[1]!='area'){
  351. $params[':'.$tableField['BIND'][1]] = $bindValue[1];
  352. if(isset($bindValue[2])&&$bindValue[2]&&$bindValue[2]!='area'){
  353. $params[':'.$tableField['BIND'][2]] = $bindValue[2];
  354. }
  355. }
  356. }
  357. }
  358. else {
  359. $params[':' . $bindParam] = $bindValue;
  360. }
  361. }
  362. return ['condition' => $condition, 'params' => $params];
  363. }
  364. /**
  365. * 筛选条件
  366. * @param string $tableName
  367. * @param array $otherParams
  368. * [
  369. * '筛选提交参数名' => '表名.字段名',
  370. * 'userName' => 'USER_INFO.USER_NAME',
  371. * ]
  372. * 或者
  373. * [
  374. * '筛选提交参数名' => ['表名.字段名', '符号'],
  375. * 'userName' => ['USER_INFO.USER_NAME', '<'],
  376. * ]
  377. * @return array
  378. */
  379. public function filterConditionBak($tableName = '', array $otherParams = []) {
  380. $dateRange = Yii::$app->request->get('dateRange', '');
  381. $condition = '';
  382. $params = [];
  383. if ($tableName) {
  384. $tableName = $tableName . '.';
  385. }
  386. if ($dateRange) {
  387. $condition .= " AND {$tableName}CREATED_AT>:CREATED_START AND {$tableName}CREATED_AT<:CREATED_END";
  388. $params[':CREATED_START'] = Date::utcToTime($dateRange[0]);
  389. $params[':CREATED_END'] = Date::utcToTime($dateRange[1]);
  390. }
  391. $requestParams = [];
  392. foreach ($otherParams as $getParam => $field) {
  393. $getValue = Yii::$app->request->get($getParam, '');
  394. $requestParams[$getParam] = $getValue;
  395. if ($getValue === 'all') $getValue = '';
  396. if ($getValue !== '') {
  397. if (is_string($field)) {
  398. $condition .= " AND $field=:" . strtoupper($getParam);
  399. $params[':' . strtoupper($getParam)] = $getValue;
  400. } elseif (is_array($field)) {
  401. if (count($field) == 1) {
  402. $condition .= " AND {$field[0]}=:" . strtoupper($getParam);
  403. $params[':' . strtoupper($getParam)] = $getValue;
  404. } elseif (count($field) == 2) {
  405. if (strtolower($field[1]) == 'in') {
  406. $getValue = Tool::filterSpecialChar($getValue);
  407. if ($getValue) {
  408. $getValue = explode(',', $getValue);
  409. $getValue = implode("','", $getValue);
  410. $getValue = "'$getValue'";
  411. $condition .= " AND {$field[0]} IN ({$getValue})";
  412. }
  413. } else {
  414. $condition .= " AND {$field[0]}{$field[1]}:" . strtoupper($getParam);
  415. $params[':' . strtoupper($getParam)] = $getValue;
  416. }
  417. }
  418. }
  419. }
  420. }
  421. // 请求的参数也一并返回
  422. $request = array_merge([
  423. 'dateRange' => $dateRange,
  424. ], $requestParams);
  425. return [
  426. 'condition' => $condition,
  427. 'params' => $params,
  428. 'request' => $request,
  429. ];
  430. }
  431. }