BaseController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. return parent::beforeAction($action);
  44. }
  45. /**
  46. * 返回结果集
  47. * @param $dataOrErrorMessage
  48. * @param int $code
  49. * @return mixed
  50. * @throws HttpException
  51. */
  52. public static function notice($dataOrErrorMessage, $code = 0) {
  53. if ($code === 0) {
  54. return $dataOrErrorMessage;
  55. } else {
  56. throw new HttpException($code, $dataOrErrorMessage, $code);
  57. }
  58. }
  59. /**
  60. * 编辑方法
  61. * @param $formModelClass
  62. * @param $successMsg
  63. * @param string|null $scenario
  64. * @param array|null $methodAndParam
  65. * [
  66. * 'edit', // form 调用对象的方法名
  67. * 'param1', // form 调用对象的方法的第一个参数
  68. * 'param2', // form 调用对象的方法的第二个参数
  69. * 'param3', // form 调用对象的方法的第三个参数
  70. * ]
  71. * @param callable|null $beforeFun
  72. * @param callable|null $afterFun
  73. * @return mixed
  74. * @throws HttpException
  75. */
  76. public static function edit($formModelClass, $successMsg, string $scenario = null, array $methodAndParam = null, callable $beforeFun = null, callable $afterFun = null) {
  77. $id = Yii::$app->request->get('id', 0);
  78. $formModel = new $formModelClass();
  79. $formModel->scenario = 'add';
  80. if ($id) {
  81. $formModel->scenario = 'edit';
  82. $formModel->id = $id;
  83. }
  84. if ($scenario !== null) {
  85. $formModel->scenario = $scenario;
  86. }
  87. if ($beforeFun) $beforeFun($formModel);
  88. if ($methodAndParam === null) {
  89. $method = 'edit';
  90. $param = [];
  91. } else {
  92. $method = $methodAndParam[0];
  93. $param = $methodAndParam;
  94. unset($param[0]);
  95. }
  96. if ($formModel->load(Yii::$app->request->post(), '') && $result = call_user_func_array([&$formModel, $method], $param)) {
  97. if ($afterFun) $afterFun($formModel, $result);
  98. return static::notice($successMsg);
  99. } else {
  100. return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 422);
  101. }
  102. }
  103. /**
  104. * 删除方法
  105. * @param $modelClass
  106. * @param callable|null $beforeFun
  107. * @param callable|null $afterFun
  108. * @param bool $isDelData
  109. * @return mixed
  110. * @throws Exception
  111. * @throws HttpException
  112. */
  113. public static function delete($modelClass, callable $beforeFun = null, callable $afterFun = null, $isDelData = true) {
  114. $selected = \Yii::$app->request->get('selected');
  115. if (!$selected) {
  116. $selected = \Yii::$app->request->post('selected');
  117. }
  118. if (!$selected) {
  119. return self::notice('必须选择一条删除数据', 500);
  120. }
  121. // 是否存在 DONT_DEL 字段
  122. if (ActiveRecord::isExistsField($modelClass, 'DONT_DEL')) {
  123. $isDontDelField = true;
  124. } else {
  125. $isDontDelField = false;
  126. }
  127. if (is_array($selected)) {
  128. if ($isDontDelField) {
  129. $condition = ['AND', ['IN', 'ID', $selected], ['<>', 'DONT_DEL', 1]];
  130. } else {
  131. $condition = ['AND', ['IN', 'ID', $selected]];
  132. }
  133. // $condition = 'ID IN ('.implode(',', $selected).') AND DONT_DEL<>1';
  134. $params = [];
  135. } else {
  136. if ($isDontDelField) {
  137. $condition = 'ID=:ID AND DONT_DEL<>1';
  138. } else {
  139. $condition = 'ID=:ID';
  140. }
  141. //$condition = ['AND', ['ID'=>$selected], ['<>', 'DONT_DEL', 1]];
  142. $params = [':ID' => $selected];
  143. }
  144. $transaction = \Yii::$app->db->beginTransaction();
  145. try {
  146. if (!is_array($selected)) {
  147. $selected = [$selected];
  148. }
  149. if ($beforeFun) $beforeFun($selected);
  150. if ($isDelData) {
  151. // 真实删除数据
  152. if (!$modelClass::deleteAll($condition, $params)) {
  153. throw new Exception('删除失败');
  154. }
  155. } else {
  156. // 设置IS_DEL字段为1
  157. $modelClass::updateAll(['IS_DEL' => 1, 'DELETED_AT' => Date::nowTime()], $condition, $params);
  158. }
  159. if ($afterFun) $afterFun($selected);
  160. $transaction->commit();
  161. return self::notice('删除成功');
  162. } catch (Exception $e) {
  163. $transaction->rollBack();
  164. return self::notice($e->getMessage(), 500);
  165. }
  166. }
  167. /**
  168. * 筛选条件
  169. * @param array $tableParams
  170. * [
  171. * '筛选提交参数名' => '表名.字段名',
  172. * 'userIds' => 'USER_INFO.USER_ID',
  173. * 'userName' => 'USER_INFO.USER_NAME',
  174. * ]
  175. *
  176. * get提交的值
  177. * [
  178. * 'userIds' => 'in,asdsa,asdsads',
  179. * 'userName' => 'like,test',
  180. * 'createdAt' => '>=,2018-11-26,date'
  181. * ]
  182. * @return array
  183. */
  184. public function filterCondition(array $tableParams = []) {
  185. $allGet = Yii::$app->request->get();
  186. $condition = '';
  187. $params = [];
  188. foreach ($tableParams as $getParam => $tableField) {
  189. if (isset($allGet[$getParam]) && $allGet[$getParam]) {
  190. $getValue = trim($allGet[$getParam], ", \t\n\r\0\x0B");
  191. $bindParam = strtoupper($getParam);
  192. if (strpos($getValue, ',') > 0) {
  193. $getValueArr = explode(',', $getValue);
  194. $getSymbol = strtoupper($getValueArr[0]);
  195. if ($getSymbol == 'IN') {
  196. $bindValueArr = $getValueArr;
  197. unset($bindValueArr[0]);
  198. $bindValue = implode("','", $bindValueArr);
  199. $bindValue = "'$bindValue'";
  200. } else {
  201. $bindValue = $getValueArr[1];
  202. if (count($getValueArr) == 3) {
  203. if ($getValueArr[2] == 'date') {
  204. $bindValue = strtotime($bindValue);
  205. }
  206. }
  207. }
  208. } else {
  209. $getSymbol = '=';
  210. $bindValue = $getValue;
  211. }
  212. if ($getSymbol == 'LIKE') {
  213. $condition .= ' AND INSTR(' . $tableField . ',:' . $bindParam . ')>0';
  214. } elseif ($getSymbol == 'IN') {
  215. $condition .= ' AND ' . $tableField . ' IN (' . $bindValue . ')';
  216. } else {
  217. $condition .= ' AND ' . $tableField . $getSymbol . ':' . $bindParam;
  218. }
  219. if ($getSymbol != 'IN') {
  220. $params[':' . $bindParam] = $bindValue;
  221. }
  222. }
  223. }
  224. return [
  225. 'condition' => $condition,
  226. 'params' => $params,
  227. 'request' => $allGet,
  228. ];
  229. }
  230. /**
  231. * 筛选条件
  232. * @param string $tableName
  233. * @param array $otherParams
  234. * [
  235. * '筛选提交参数名' => '表名.字段名',
  236. * 'userName' => 'USER_INFO.USER_NAME',
  237. * ]
  238. * 或者
  239. * [
  240. * '筛选提交参数名' => ['表名.字段名', '符号'],
  241. * 'userName' => ['USER_INFO.USER_NAME', '<'],
  242. * ]
  243. * @return array
  244. */
  245. public function filterConditionBak($tableName = '', array $otherParams = []) {
  246. $dateRange = Yii::$app->request->get('dateRange', '');
  247. $condition = '';
  248. $params = [];
  249. if ($tableName) {
  250. $tableName = $tableName . '.';
  251. }
  252. if ($dateRange) {
  253. $condition .= " AND {$tableName}CREATED_AT>:CREATED_START AND {$tableName}CREATED_AT<:CREATED_END";
  254. $params[':CREATED_START'] = Date::utcToTime($dateRange[0]);
  255. $params[':CREATED_END'] = Date::utcToTime($dateRange[1]);
  256. }
  257. $requestParams = [];
  258. foreach ($otherParams as $getParam => $field) {
  259. $getValue = Yii::$app->request->get($getParam, '');
  260. $requestParams[$getParam] = $getValue;
  261. if ($getValue === 'all') $getValue = '';
  262. if ($getValue !== '') {
  263. if (is_string($field)) {
  264. $condition .= " AND $field=:" . strtoupper($getParam);
  265. $params[':' . strtoupper($getParam)] = $getValue;
  266. } elseif (is_array($field)) {
  267. if (count($field) == 1) {
  268. $condition .= " AND {$field[0]}=:" . strtoupper($getParam);
  269. $params[':' . strtoupper($getParam)] = $getValue;
  270. } elseif (count($field) == 2) {
  271. if (strtolower($field[1]) == 'in') {
  272. $getValue = Tool::filterSpecialChar($getValue);
  273. if ($getValue) {
  274. $getValue = explode(',', $getValue);
  275. $getValue = implode("','", $getValue);
  276. $getValue = "'$getValue'";
  277. $condition .= " AND {$field[0]} IN ({$getValue})";
  278. }
  279. } else {
  280. $condition .= " AND {$field[0]}{$field[1]}:" . strtoupper($getParam);
  281. $params[':' . strtoupper($getParam)] = $getValue;
  282. }
  283. }
  284. }
  285. }
  286. }
  287. // 请求的参数也一并返回
  288. $request = array_merge([
  289. 'dateRange' => $dateRange,
  290. ], $requestParams);
  291. return [
  292. 'condition' => $condition,
  293. 'params' => $params,
  294. 'request' => $request,
  295. ];
  296. }
  297. }