BaseController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 frontendApi\modules\v1\models\User;
  13. use Yii;
  14. use yii\db\Exception;
  15. use yii\web\ForbiddenHttpException;
  16. use yii\web\HttpException;
  17. class BaseController extends \yii\rest\ActiveController {
  18. /**
  19. * 不让控制器直接选择model类直接返回数据
  20. * @return array
  21. */
  22. public function actions() {
  23. return [];
  24. }
  25. /**
  26. * @throws ForbiddenHttpException
  27. */
  28. protected function forbiddenQuicklyUser() {
  29. $isQuickly = User::isQuicklyLogin();
  30. $requestMethod = Yii::$app->request->getMethod();
  31. if ($isQuickly == 1 && strtoupper($requestMethod) != 'GET') {
  32. throw new ForbiddenHttpException('快速登录的会员无法进行任何操作!');
  33. }
  34. }
  35. /**
  36. * @param $action
  37. * @return bool
  38. * @throws ForbiddenHttpException
  39. * @throws \yii\web\BadRequestHttpException
  40. */
  41. public function beforeAction($action) {
  42. $this->forbiddenQuicklyUser();
  43. // 增加的判断用户登录的操作间隔是否大于十分钟
  44. if (Yii::$app->getUser()->getUserInfo()){
  45. $adminId = Yii::$app->getUser()->getUserInfo()['id'];
  46. $redisAdminKey = 'user-'.$adminId;
  47. $lastTime = '';
  48. if (!Yii::$app->tokenRedis->hget($redisAdminKey, 'lastTime')) {
  49. $lastTime = time();
  50. }else{
  51. $lastTime = Yii::$app->tokenRedis->hget($redisAdminKey, 'lastTime');
  52. }
  53. $currentTime = time();
  54. $timeOut = 15 * 60 ;
  55. if ($currentTime - $lastTime > $timeOut) {
  56. return self::notice('Connection not operated for too long', 402);
  57. } else {
  58. Yii::$app->tokenRedis->hset($redisAdminKey, 'lastTime', time());
  59. }
  60. }
  61. return parent::beforeAction($action);
  62. }
  63. /**
  64. * 返回结果集
  65. * @param $dataOrErrorMessage
  66. * @param int $code
  67. * @return mixed
  68. * @throws HttpException
  69. */
  70. public static function notice($dataOrErrorMessage, $code = 0) {
  71. if ($code === 0) {
  72. return $dataOrErrorMessage;
  73. } else {
  74. throw new HttpException($code, $dataOrErrorMessage, $code);
  75. }
  76. }
  77. /**
  78. * 编辑方法
  79. * @param $formModelClass
  80. * @param $successMsg
  81. * @param string|null $scenario
  82. * @param array|null $methodAndParam
  83. * [
  84. * 'edit', // form 调用对象的方法名
  85. * 'param1', // form 调用对象的方法的第一个参数
  86. * 'param2', // form 调用对象的方法的第二个参数
  87. * 'param3', // form 调用对象的方法的第三个参数
  88. * ]
  89. * @param callable|null $beforeFun
  90. * @param callable|null $afterFun
  91. * @return mixed
  92. * @throws HttpException
  93. */
  94. public static function edit($formModelClass, $successMsg, string $scenario = null, array $methodAndParam = null, callable $beforeFun = null, callable $afterFun = null) {
  95. $id = Yii::$app->request->get('id', 0);
  96. $formModel = new $formModelClass();
  97. $formModel->scenario = 'add';
  98. if ($id) {
  99. $formModel->scenario = 'edit';
  100. $formModel->id = $id;
  101. }
  102. if ($scenario !== null) {
  103. $formModel->scenario = $scenario;
  104. }
  105. if ($beforeFun) $beforeFun($formModel);
  106. if ($methodAndParam === null) {
  107. $method = 'edit';
  108. $param = [];
  109. } else {
  110. $method = $methodAndParam[0];
  111. $param = $methodAndParam;
  112. unset($param[0]);
  113. }
  114. if ($formModel->load(Yii::$app->request->post(), '') && $result = call_user_func_array([&$formModel, $method], $param)) {
  115. if ($afterFun) $afterFun($formModel, $result);
  116. return static::notice($successMsg);
  117. } else {
  118. return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 422);
  119. }
  120. }
  121. /**
  122. * 删除方法
  123. * @param $modelClass
  124. * @param callable|null $beforeFun
  125. * @param callable|null $afterFun
  126. * @param bool $isDelData
  127. * @return mixed
  128. * @throws Exception
  129. * @throws HttpException
  130. */
  131. public static function delete($modelClass, callable $beforeFun = null, callable $afterFun = null, $isDelData = true) {
  132. $selected = \Yii::$app->request->get('selected');
  133. if (!$selected) {
  134. $selected = \Yii::$app->request->post('selected');
  135. }
  136. if (!$selected) {
  137. return self::notice('必须选择一条删除数据', 500);
  138. }
  139. // 是否存在 DONT_DEL 字段
  140. if (ActiveRecord::isExistsField($modelClass, 'DONT_DEL')) {
  141. $isDontDelField = true;
  142. } else {
  143. $isDontDelField = false;
  144. }
  145. if (is_array($selected)) {
  146. if ($isDontDelField) {
  147. $condition = ['AND', ['IN', 'ID', $selected], ['<>', 'DONT_DEL', 1]];
  148. } else {
  149. $condition = ['AND', ['IN', 'ID', $selected]];
  150. }
  151. // $condition = 'ID IN ('.implode(',', $selected).') AND DONT_DEL<>1';
  152. $params = [];
  153. } else {
  154. if ($isDontDelField) {
  155. $condition = 'ID=:ID AND DONT_DEL<>1';
  156. } else {
  157. $condition = 'ID=:ID';
  158. }
  159. //$condition = ['AND', ['ID'=>$selected], ['<>', 'DONT_DEL', 1]];
  160. $params = [':ID' => $selected];
  161. }
  162. $transaction = \Yii::$app->db->beginTransaction();
  163. try {
  164. if (!is_array($selected)) {
  165. $selected = [$selected];
  166. }
  167. if ($beforeFun) $beforeFun($selected);
  168. if ($isDelData) {
  169. // 真实删除数据
  170. if (!$modelClass::deleteAll($condition, $params)) {
  171. throw new Exception('删除失败');
  172. }
  173. } else {
  174. // 设置IS_DEL字段为1
  175. $modelClass::updateAll(['IS_DEL' => 1, 'DELETED_AT' => Date::nowTime()], $condition, $params);
  176. }
  177. if ($afterFun) $afterFun($selected);
  178. $transaction->commit();
  179. return self::notice('删除成功');
  180. } catch (Exception $e) {
  181. $transaction->rollBack();
  182. return self::notice($e->getMessage(), 500);
  183. }
  184. }
  185. /**
  186. * 筛选条件
  187. * @param array $tableParams
  188. * [
  189. * '筛选提交参数名' => '表名.字段名',
  190. * 'userIds' => 'USER_INFO.USER_ID',
  191. * 'userName' => 'USER_INFO.USER_NAME',
  192. * ]
  193. *
  194. * get提交的值
  195. * [
  196. * 'userIds' => 'in,asdsa,asdsads',
  197. * 'userName' => 'like,test',
  198. * 'createdAt' => '>=,2018-11-26,date'
  199. * ]
  200. * @return array
  201. */
  202. public function filterCondition(array $tableParams = []) {
  203. $allGet = Yii::$app->request->get();
  204. $condition = '';
  205. $params = [];
  206. foreach ($tableParams as $getParam => $tableField) {
  207. if (isset($allGet[$getParam]) && $allGet[$getParam]) {
  208. $getValue = trim($allGet[$getParam], ", \t\n\r\0\x0B");
  209. $bindParam = strtoupper($getParam);
  210. if (strpos($getValue, ',') > 0) {
  211. $getValueArr = explode(',', $getValue);
  212. $getSymbol = strtoupper($getValueArr[0]);
  213. if ($getSymbol == 'IN') {
  214. $bindValueArr = $getValueArr;
  215. unset($bindValueArr[0]);
  216. $bindValue = implode("','", $bindValueArr);
  217. $bindValue = "'$bindValue'";
  218. } else {
  219. $bindValue = $getValueArr[1];
  220. if (count($getValueArr) == 3) {
  221. if ($getValueArr[2] == 'date') {
  222. $bindValue = strtotime($bindValue);
  223. }
  224. }
  225. }
  226. } else {
  227. $getSymbol = '=';
  228. $bindValue = $getValue;
  229. }
  230. if ($getSymbol == 'LIKE') {
  231. $condition .= ' AND INSTR(' . $tableField . ',:' . $bindParam . ')>0';
  232. } elseif ($getSymbol == 'IN') {
  233. $condition .= ' AND ' . $tableField . ' IN (' . $bindValue . ')';
  234. } else {
  235. $condition .= ' AND ' . $tableField . $getSymbol . ':' . $bindParam;
  236. }
  237. if ($getSymbol != 'IN') {
  238. $params[':' . $bindParam] = $bindValue;
  239. }
  240. }
  241. }
  242. return [
  243. 'condition' => $condition,
  244. 'params' => $params,
  245. 'request' => $allGet,
  246. ];
  247. }
  248. /**
  249. * 筛选条件
  250. * @param string $tableName
  251. * @param array $otherParams
  252. * [
  253. * '筛选提交参数名' => '表名.字段名',
  254. * 'userName' => 'USER_INFO.USER_NAME',
  255. * ]
  256. * 或者
  257. * [
  258. * '筛选提交参数名' => ['表名.字段名', '符号'],
  259. * 'userName' => ['USER_INFO.USER_NAME', '<'],
  260. * ]
  261. * @return array
  262. */
  263. public function filterConditionBak($tableName = '', array $otherParams = []) {
  264. $dateRange = Yii::$app->request->get('dateRange', '');
  265. $condition = '';
  266. $params = [];
  267. if ($tableName) {
  268. $tableName = $tableName . '.';
  269. }
  270. if ($dateRange) {
  271. $condition .= " AND {$tableName}CREATED_AT>:CREATED_START AND {$tableName}CREATED_AT<:CREATED_END";
  272. $params[':CREATED_START'] = Date::utcToTime($dateRange[0]);
  273. $params[':CREATED_END'] = Date::utcToTime($dateRange[1]);
  274. }
  275. $requestParams = [];
  276. foreach ($otherParams as $getParam => $field) {
  277. $getValue = Yii::$app->request->get($getParam, '');
  278. $requestParams[$getParam] = $getValue;
  279. if ($getValue === 'all') $getValue = '';
  280. if ($getValue !== '') {
  281. if (is_string($field)) {
  282. $condition .= " AND $field=:" . strtoupper($getParam);
  283. $params[':' . strtoupper($getParam)] = $getValue;
  284. } elseif (is_array($field)) {
  285. if (count($field) == 1) {
  286. $condition .= " AND {$field[0]}=:" . strtoupper($getParam);
  287. $params[':' . strtoupper($getParam)] = $getValue;
  288. } elseif (count($field) == 2) {
  289. if (strtolower($field[1]) == 'in') {
  290. $getValue = Tool::filterSpecialChar($getValue);
  291. if ($getValue) {
  292. $getValue = explode(',', $getValue);
  293. $getValue = implode("','", $getValue);
  294. $getValue = "'$getValue'";
  295. $condition .= " AND {$field[0]} IN ({$getValue})";
  296. }
  297. } else {
  298. $condition .= " AND {$field[0]}{$field[1]}:" . strtoupper($getParam);
  299. $params[':' . strtoupper($getParam)] = $getValue;
  300. }
  301. }
  302. }
  303. }
  304. }
  305. // 请求的参数也一并返回
  306. $request = array_merge([
  307. 'dateRange' => $dateRange,
  308. ], $requestParams);
  309. return [
  310. 'condition' => $condition,
  311. 'params' => $params,
  312. 'request' => $request,
  313. ];
  314. }
  315. }