BaseController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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('权限不足', 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. * @param $modelClass
  120. * @param callable|null $beforeFun
  121. * @param callable|null $afterFun
  122. * @param bool $isDelData
  123. * @return mixed
  124. * @throws Exception
  125. * @throws HttpException
  126. */
  127. public static function delete($modelClass, callable $beforeFun = null, callable $afterFun = null, $isDelData = true) {
  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('必须选择一条删除数据', 500);
  134. }
  135. // 是否存在 DONT_DEL 字段
  136. if (ActiveRecord::isExistsField($modelClass, 'DONT_DEL')) {
  137. $isDontDelField = true;
  138. } else {
  139. $isDontDelField = false;
  140. }
  141. if (is_array($selected)) {
  142. if ($isDontDelField) {
  143. $condition = ['AND', ['IN', 'ID', $selected], ['<>', 'DONT_DEL', 1]];
  144. } else {
  145. $condition = ['AND', ['IN', 'ID', $selected]];
  146. }
  147. // $condition = 'ID IN ('.implode(',', $selected).') AND DONT_DEL<>1';
  148. $params = [];
  149. } else {
  150. if ($isDontDelField) {
  151. $condition = 'ID=:ID AND DONT_DEL<>1';
  152. } else {
  153. $condition = 'ID=:ID';
  154. }
  155. //$condition = ['AND', ['ID'=>$selected], ['<>', 'DONT_DEL', 1]];
  156. $params = [':ID' => $selected];
  157. }
  158. $transaction = \Yii::$app->db->beginTransaction();
  159. try {
  160. if (!is_array($selected)) {
  161. $selected = [$selected];
  162. }
  163. if ($beforeFun) $beforeFun($selected);
  164. if ($isDelData) {
  165. // 真实删除数据
  166. if (!$modelClass::deleteAll($condition, $params)) {
  167. throw new Exception('删除失败');
  168. }
  169. } else {
  170. // 设置IS_DEL字段为1
  171. $modelClass::updateAll(['IS_DEL' => 1, 'DELETED_AT' => Date::nowTime()], $condition, $params);
  172. }
  173. if ($afterFun) $afterFun($selected);
  174. $transaction->commit();
  175. return self::notice('删除成功');
  176. } catch (Exception $e) {
  177. $transaction->rollBack();
  178. return self::notice($e->getMessage(), 500);
  179. }
  180. }
  181. /**
  182. * 筛选条件
  183. * @param array $tableParams
  184. * [
  185. * '筛选提交参数名' => '表名.字段名',
  186. * 'userIds' => 'USER_INFO.USER_ID',
  187. * 'userName' => 'USER_INFO.USER_NAME',
  188. * ]
  189. *
  190. * get提交的值
  191. * [
  192. * 'userIds' => 'in,asdsa,asdsads',
  193. * 'userName' => 'like,test',
  194. * 'createdAt' => '>=,2018-11-26,date'
  195. * ]
  196. * @return array
  197. */
  198. public function filterCondition(array $tableParams = []) {
  199. $allGet = Yii::$app->request->get();
  200. $condition = '';
  201. $params = [];
  202. foreach ($tableParams as $getParam => $tableField) {
  203. if (isset($allGet[$getParam]) && $allGet[$getParam]) {
  204. $getValue = trim($allGet[$getParam], ", \t\n\r\0\x0B");
  205. $bindParam = strtoupper($getParam);
  206. if (strpos($getValue, '|') > 0) {
  207. $condition .= ' AND (';
  208. $chidValueArr = explode('|', $getValue);
  209. foreach ($chidValueArr as $k => $value) {
  210. if ($k == 0) {
  211. $result = $this->_getConditionAndParams($value, $tableField, $bindParam . $k, '');
  212. } else {
  213. $result = $this->_getConditionAndParams($value, $tableField, $bindParam . $k, 'OR');
  214. }
  215. $condition .= $result['condition'];
  216. $params += $result['params'];
  217. }
  218. $condition .= ')';
  219. } else {
  220. $result = $this->_getConditionAndParams($getValue, $tableField, $bindParam);
  221. $condition .= $result['condition'];
  222. $params += $result['params'];
  223. }
  224. }
  225. }
  226. return [
  227. 'condition' => $condition,
  228. 'params' => $params,
  229. 'request' => $allGet,
  230. ];
  231. }
  232. /**
  233. * 获取条件
  234. * @param $getValue
  235. * @param $tableField
  236. * @param $bindParam
  237. * @param string $relation
  238. * @return array
  239. */
  240. private function _getConditionAndParams($getValue, $tableField, $bindParam, $relation = 'AND') {
  241. $condition = '';
  242. $params = [];
  243. $isDate = false;
  244. $filterModel = '';
  245. if (strpos($getValue, ',') > 0) {
  246. $getValueArr = explode(',', $getValue);
  247. $getSymbol = strtoupper($getValueArr[0]);
  248. if ($getSymbol == 'IN') {
  249. $bindValueArr = $getValueArr;
  250. unset($bindValueArr[0]);
  251. $bindValue = implode("','", $bindValueArr);
  252. $bindValue = "'$bindValue'";
  253. } else {
  254. $bindValue = $getValueArr[1];
  255. $filterModel = end($getValueArr);
  256. reset($getValueArr);
  257. if($filterModel == 'date'){
  258. if( $getSymbol !== '>=' && $getSymbol !== '<=' && $getSymbol !== '>' && $getSymbol !== '<' ) {
  259. throw new \Exception("日期筛选格式不对");
  260. }
  261. $bindValue = strtotime($getValueArr[1]);
  262. $isDate = true;
  263. $relation = $relation ? 'AND' : '';
  264. }
  265. elseif($filterModel == 'area'){
  266. $bindValue = array_slice($getValueArr, 1, 3);
  267. }
  268. }
  269. } else {
  270. $getSymbol = '=';
  271. $bindValue = $getValue;
  272. }
  273. if ($getSymbol == 'LIKE') {
  274. $condition .= ' ' . $relation . ' INSTR(' . $tableField . ',:' . $bindParam . ')>0';
  275. } elseif ($getSymbol == strtoupper('notLike')) {
  276. $condition .= ' ' . $relation . ' INSTR(' . $tableField . ',:' . $bindParam . ')=0';
  277. } elseif ($getSymbol == 'IN') {
  278. $condition .= ' ' . $relation . ' ' . $tableField . ' IN (' . $bindValue . ')';
  279. } else {
  280. if ($isDate && $getSymbol == '=') {
  281. $condition .= ' ' . $relation . ' ' . $tableField . '>=:' . $bindParam . 's';
  282. $condition .= ' AND ' . $tableField . '<=:' . $bindParam . 'e';
  283. }
  284. elseif($filterModel == 'area'){
  285. if($bindValue[0]){
  286. $condition .= ' AND '.$tableField['FIELD'][0].'=:'.$tableField['BIND'][0];
  287. if(isset($bindValue[1])&&$bindValue[1]&&$bindValue[1]!='area'){
  288. $condition .= ' AND '.$tableField['FIELD'][1].'=:'.$tableField['BIND'][1];
  289. if(isset($bindValue[2])&&$bindValue[2]&&$bindValue[2]!='area'){
  290. $condition .= ' AND '.$tableField['FIELD'][2].'=:'.$tableField['BIND'][2];
  291. }
  292. }
  293. }
  294. }
  295. else {
  296. if($getSymbol!=='=' && $relation=='OR'){
  297. $relation = 'AND';
  298. }
  299. $condition .= ' ' . $relation . ' ' . $tableField . $getSymbol . ':' . $bindParam;
  300. }
  301. }
  302. if ($getSymbol != 'IN') {
  303. if ($isDate && $getSymbol == '=') {
  304. $params[':' . $bindParam . 's'] = $bindValue;
  305. $params[':' . $bindParam . 'e'] = $bindValue + 86399;
  306. }
  307. if ($filterModel == 'area') {
  308. if($bindValue[0]){
  309. $params[':'.$tableField['BIND'][0]] = $bindValue[0];
  310. if(isset($bindValue[1])&&$bindValue[1]&&$bindValue[1]!='area'){
  311. $params[':'.$tableField['BIND'][1]] = $bindValue[1];
  312. if(isset($bindValue[2])&&$bindValue[2]&&$bindValue[2]!='area'){
  313. $params[':'.$tableField['BIND'][2]] = $bindValue[2];
  314. }
  315. }
  316. }
  317. }
  318. else {
  319. $params[':' . $bindParam] = $bindValue;
  320. }
  321. }
  322. return ['condition' => $condition, 'params' => $params];
  323. }
  324. /**
  325. * 筛选条件
  326. * @param string $tableName
  327. * @param array $otherParams
  328. * [
  329. * '筛选提交参数名' => '表名.字段名',
  330. * 'userName' => 'USER_INFO.USER_NAME',
  331. * ]
  332. * 或者
  333. * [
  334. * '筛选提交参数名' => ['表名.字段名', '符号'],
  335. * 'userName' => ['USER_INFO.USER_NAME', '<'],
  336. * ]
  337. * @return array
  338. */
  339. public function filterConditionBak($tableName = '', array $otherParams = []) {
  340. $dateRange = Yii::$app->request->get('dateRange', '');
  341. $condition = '';
  342. $params = [];
  343. if ($tableName) {
  344. $tableName = $tableName . '.';
  345. }
  346. if ($dateRange) {
  347. $condition .= " AND {$tableName}CREATED_AT>:CREATED_START AND {$tableName}CREATED_AT<:CREATED_END";
  348. $params[':CREATED_START'] = Date::utcToTime($dateRange[0]);
  349. $params[':CREATED_END'] = Date::utcToTime($dateRange[1]);
  350. }
  351. $requestParams = [];
  352. foreach ($otherParams as $getParam => $field) {
  353. $getValue = Yii::$app->request->get($getParam, '');
  354. $requestParams[$getParam] = $getValue;
  355. if ($getValue === 'all') $getValue = '';
  356. if ($getValue !== '') {
  357. if (is_string($field)) {
  358. $condition .= " AND $field=:" . strtoupper($getParam);
  359. $params[':' . strtoupper($getParam)] = $getValue;
  360. } elseif (is_array($field)) {
  361. if (count($field) == 1) {
  362. $condition .= " AND {$field[0]}=:" . strtoupper($getParam);
  363. $params[':' . strtoupper($getParam)] = $getValue;
  364. } elseif (count($field) == 2) {
  365. if (strtolower($field[1]) == 'in') {
  366. $getValue = Tool::filterSpecialChar($getValue);
  367. if ($getValue) {
  368. $getValue = explode(',', $getValue);
  369. $getValue = implode("','", $getValue);
  370. $getValue = "'$getValue'";
  371. $condition .= " AND {$field[0]} IN ({$getValue})";
  372. }
  373. } else {
  374. $condition .= " AND {$field[0]}{$field[1]}:" . strtoupper($getParam);
  375. $params[':' . strtoupper($getParam)] = $getValue;
  376. }
  377. }
  378. }
  379. }
  380. }
  381. // 请求的参数也一并返回
  382. $request = array_merge([
  383. 'dateRange' => $dateRange,
  384. ], $requestParams);
  385. return [
  386. 'condition' => $condition,
  387. 'params' => $params,
  388. 'request' => $request,
  389. ];
  390. }
  391. }