Base.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <?php
  2. /**
  3. * +----------------------------------------------------------------------
  4. * | 基础控制器
  5. * +----------------------------------------------------------------------
  6. * AUTHOR: huwhois
  7. * EMAIL: huwhois@163.com
  8. * DATETIME: 2020/03/08
  9. */
  10. declare(strict_types=1);
  11. namespace app\controller\sys;
  12. // 引入框架内置类
  13. use think\App;
  14. use think\exception\HttpResponseException;
  15. use think\exception\ValidateException;
  16. use think\facade\Config;
  17. use think\facade\Request;
  18. use think\facade\Session;
  19. use think\facade\View;
  20. use think\Response;
  21. use think\Validate;
  22. use app\model\SysMenu;
  23. /**
  24. * 控制器基础类
  25. */
  26. abstract class Base
  27. {
  28. // use \liliuwei\think\Jump;
  29. /**
  30. * Request实例
  31. * @var \think\Request
  32. */
  33. protected $request;
  34. /**
  35. * 应用实例
  36. * @var \think\App
  37. */
  38. protected $app;
  39. /**
  40. * 是否批量验证
  41. * @var bool
  42. */
  43. protected $batchValidate = false;
  44. /**
  45. * 控制器中间件
  46. * @var array
  47. */
  48. protected $middleware = ['app\middleware\Admin'];
  49. // /**
  50. // * 分页数量
  51. // * @var int
  52. // */
  53. // protected $pageSize = 0;
  54. /**
  55. * 系统设置
  56. * @var array
  57. */
  58. protected $system = [];
  59. /**
  60. * 用户信息
  61. */
  62. protected $sysUser;
  63. protected $modelName;
  64. /**
  65. * 构造方法
  66. * @access public
  67. * @param App $app 应用对象
  68. */
  69. public function __construct(App $app)
  70. {
  71. $this->app = $app;
  72. $this->request = $this->app->request;
  73. // 控制器初始化
  74. $this->initialize();
  75. }
  76. // 初始化
  77. protected function initialize()
  78. {
  79. $eng = View::engine();
  80. $eng->layout('sys/layout');
  81. // 左侧菜单
  82. $rid = Session::get('adminuser.roleid');
  83. $menus = $rid !=null ? SysMenu::getUserMenuList($rid) : [];
  84. $controller = str_replace("sys.", "", strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', Request::controller())));
  85. $action = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', Request::action()));
  86. $route = $controller . '/' . $action;
  87. $breadCrumb = SysMenu::getBreadCrumb($route);
  88. // layer open
  89. if (Request::has('_layer')) {
  90. View::assign('layer', true);
  91. } else {
  92. View::assign('layer', false);
  93. }
  94. // 查询系统设置
  95. $system = \app\model\System::find(1);
  96. $this->system = $system;
  97. View::assign([
  98. 'active_pid' => $breadCrumb['active_pid'],
  99. 'breadCrumb' => $breadCrumb['breadCrumb'],
  100. 'menus' => $menus,
  101. 'system' => $system,
  102. 'sys_version' => Config::get('app.sys_version'),
  103. 'default_lang' => env('lang.default_lang', 'en')
  104. ]);
  105. }
  106. /**
  107. * 验证数据
  108. * @access protected
  109. * @param array $data 数据
  110. * @param string|array $validate 验证器名或者验证规则数组
  111. * @param array $message 提示信息
  112. * @param bool $batch 是否批量验证
  113. * @return array|string|true
  114. * @throws ValidateException
  115. */
  116. protected function validate(array $data, $validate, array $message = [], bool $batch = false)
  117. {
  118. if (is_array($validate)) {
  119. $v = new Validate();
  120. $v->rule($validate);
  121. } else {
  122. if (strpos($validate, '.')) {
  123. // 支持场景
  124. list($validate, $scene) = explode('.', $validate);
  125. }
  126. $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
  127. $v = new $class();
  128. if (!empty($scene)) {
  129. $v->scene($scene);
  130. }
  131. }
  132. $v->message($message);
  133. //是否批量验证
  134. if ($batch || $this->batchValidate) {
  135. $v->batch(true);
  136. }
  137. $result = $v->failException(false)->check($data);
  138. if (true !== $result) {
  139. return $v->getError();
  140. } else {
  141. return $result;
  142. }
  143. }
  144. /**
  145. * 操作成功跳转的快捷方法
  146. * @access protected
  147. * @param mixed $msg 提示信息
  148. * @param string $url 跳转的URL地址
  149. * @param mixed $data 返回的数据
  150. * @param integer $wait 跳转等待时间
  151. * @param array $header 发送的Header信息
  152. * @return void
  153. */
  154. protected function success($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
  155. {
  156. if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
  157. $url = $_SERVER["HTTP_REFERER"];
  158. } elseif ($url) {
  159. $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : (string)$this->app->route->buildUrl($url);
  160. }
  161. $result = [
  162. 'code' => 0,
  163. 'msg' => $msg,
  164. 'data' => $data,
  165. 'url' => $url,
  166. 'wait' => $wait,
  167. ];
  168. $type = $this->request->isJson() || $this->request->isAjax() ? 'json' : 'html';
  169. // 把跳转模板的渲染下沉,这样在 response_send 行为里通过getData()获得的数据是一致性的格式
  170. if ('html' == strtolower($type)) {
  171. $type = 'view';
  172. $response = Response::create($this->app->config->get('jump.dispatch_success_tmpl'), $type)->assign($result)->header($header);
  173. } else {
  174. $response = Response::create($result, $type)->header($header);
  175. }
  176. throw new HttpResponseException($response);
  177. }
  178. /**
  179. * 操作错误跳转的快捷方法
  180. * @access protected
  181. * @param mixed $msg 提示信息
  182. * @param string $url 跳转的URL地址
  183. * @param mixed $data 返回的数据
  184. * @param integer $wait 跳转等待时间
  185. * @param array $header 发送的Header信息
  186. * @return void
  187. */
  188. protected function error($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
  189. {
  190. if (is_null($url)) {
  191. $url = $this->request->isAjax() ? '' : 'javascript:history.back(-1);';
  192. } elseif ($url) {
  193. $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : (string)$this->app->route->buildUrl($url);
  194. }
  195. $result = [
  196. 'code' => 1,
  197. 'msg' => $msg,
  198. 'data' => $data,
  199. 'url' => $url,
  200. 'wait' => $wait,
  201. ];
  202. $type = $this->request->isJson() || $this->request->isAjax() ? 'json' : 'html';
  203. if ('html' == strtolower($type)) {
  204. $type = 'view';
  205. $response = Response::create($this->app->config->get('jump.dispatch_error_tmpl'), $type)->assign($result)->header($header);
  206. } else {
  207. $response = Response::create($result, $type)->header($header);
  208. }
  209. throw new HttpResponseException($response);
  210. }
  211. // /**
  212. // * 返回封装后的API数据到客户端
  213. // * @param mixed $data 要返回的数据
  214. // * @param integer $code 返回的code
  215. // * @param mixed $msg 提示信息
  216. // * @param string $type 返回数据格式
  217. // * @param array $header 发送的Header信息
  218. // * @return Response
  219. // */
  220. // protected function result($data, int $code = 0, $msg = '', string $type = '', array $header = []): Response
  221. // {
  222. // $result = [
  223. // 'code' => $code,
  224. // 'msg' => $msg,
  225. // 'time' => time(),
  226. // 'data' => $data,
  227. // ];
  228. // $type = $type ?: 'json';
  229. // $response = Response::create($result, $type)->header($header);
  230. // throw new HttpResponseException($response);
  231. // }
  232. // // 列表
  233. // public function index()
  234. // {
  235. // // 获取主键
  236. // $pk = MakeBuilder::getPrimarykey($this->tableName);
  237. // // 获取列表数据
  238. // $columns = MakeBuilder::getListColumns($this->tableName);
  239. // // 获取搜索数据
  240. // $search = MakeBuilder::getListSearch($this->tableName);
  241. // // 获取当前模块信息
  242. // $model = '\app\model\\' . $this->modelName;
  243. // $module = \app\model\Module::where('table_name', $this->tableName)->find();
  244. // // 搜索
  245. // if (Request::param('getList') == 1) {
  246. // $where = MakeBuilder::getListWhere($this->tableName);
  247. // $orderByColumn = Request::param('orderByColumn') ?? $pk;
  248. // $isAsc = Request::param('isAsc') ?? 'desc';
  249. // return $model::getList($where, $this->pageSize, [$orderByColumn => $isAsc]);
  250. // }
  251. // // 检测单页模式
  252. // $isSingle = MakeBuilder::checkSingle($this->modelName);
  253. // if ($isSingle) {
  254. // return $this->jump($isSingle);
  255. // }
  256. // // 获取新增地址
  257. // $addUlr = MakeBuilder::getAddUrl($this->tableName);
  258. // // 构建页面
  259. // return TableBuilder::getInstance()
  260. // ->setUniqueId($pk) // 设置主键
  261. // ->addColumns($columns) // 添加列表字段数据
  262. // ->setSearch($search) // 添加头部搜索
  263. // ->addColumn('right_button', '操作', 'btn') // 启用右侧操作列
  264. // ->addRightButtons($module->right_button) // 设置右侧操作列
  265. // ->addTopButtons($module->top_button) // 设置顶部按钮组
  266. // ->setAddUrl($addUlr) // 设置新增地址
  267. // ->fetch();
  268. // }
  269. /**
  270. * 新增 or 修改
  271. * @param int $id info id
  272. * @return mix
  273. */
  274. public function save($id = 0)
  275. {
  276. if ($this->app->request->isPost()) {
  277. $params = $this->app->request->param();
  278. try {
  279. $id = $params['id'];
  280. unset($params['id']);
  281. if ($id != 0) {
  282. $this->modelName::update($params, ['id' => $id]);
  283. } else {
  284. $this->modelName::create($params);
  285. }
  286. } catch (\Exception $e) {
  287. $msg = $e->getMessage();
  288. $this->error("错误提示:".$msg);
  289. }
  290. $this->success('操作成功', (String)url('index'));
  291. } else {
  292. if ($id != 0) {
  293. $data = $this->modelName::find($id);
  294. } else {
  295. $data = null;
  296. }
  297. View::assign('data', $data);
  298. return View::fetch();
  299. }
  300. }
  301. /**
  302. * 删除
  303. * @param int|array $id info id
  304. * @return array
  305. */
  306. public function delete($id)
  307. {
  308. if (Request::isPost()) {
  309. $model = '\app\model\\' . $this->modelName;
  310. if ($model ::destroy($id)) {
  311. return ['code' => 0,'msg'=>'删除成功'];
  312. } else {
  313. return ['code' => 1,'msg'=>'删除失败'];
  314. }
  315. }
  316. }
  317. // 排序
  318. public function sort()
  319. {
  320. if (Request::isPost()) {
  321. $param = Request::param();
  322. $model = '\app\model\\' . $this->modelName;
  323. return $model::sorts($param);
  324. }
  325. }
  326. // 状态变更
  327. public function status(int $id)
  328. {
  329. if (Request::isPost()) {
  330. $model = '\app\model\\' . $this->modelName;
  331. return $model::state($id);
  332. }
  333. }
  334. // // 导出
  335. // public function export()
  336. // {
  337. // \app\model\Base::export($this->tableName, $this->modelName);
  338. // }
  339. // 获取当前登录用户信息
  340. protected function getSysUser()
  341. {
  342. if (!$this->sysUser) {
  343. $this->sysUser = \app\model\SysUser::where('userid', session('adminuser.userid'))->find();
  344. }
  345. return $this->sysUser;
  346. }
  347. }