BaseController.php 14 KB

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