Base.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. // // pjax
  95. // if (Request::has('_pjax')) {
  96. // View::assign(['pjax' => true]);
  97. // } else {
  98. // View::assign(['pjax' => false]);
  99. // }
  100. // 内容管理,获取栏目列表
  101. // if (class_exists('\app\model\Cate')) {
  102. // $cates = \app\model\Cate::getList();
  103. // }
  104. // View::assign(['cates' => unlimitedForLayer($cates['data'] ?? [])]);
  105. // index应用地址
  106. // $domainBind = Config::get('app.domain_bind');
  107. // if ($domainBind) {
  108. // $domainBindKey = array_search('index', $domainBind);
  109. // $domainBindKey = $domainBindKey == '*' ? 'www.' : ($domainBindKey ? $domainBindKey . '.' : '');
  110. // $indexUrl = Request::scheme() . '://' . $domainBindKey . Request::rootDomain() . '/';
  111. // }
  112. // View::assign(['indexUrl' => $indexUrl ?? '/']);
  113. // 查询系统设置
  114. $system = \app\model\System::find(1);
  115. $this->system = $system;
  116. View::assign([
  117. 'active_pid' => $breadCrumb['active_pid'],
  118. 'breadCrumb' => $breadCrumb['breadCrumb'],
  119. 'menus' => $menus,
  120. 'system' => $system,
  121. 'sys_version' => Config::get('app.sys_version'),
  122. 'default_lang' => env('lang.default_lang', 'en')
  123. ]);
  124. }
  125. /**
  126. * 验证数据
  127. * @access protected
  128. * @param array $data 数据
  129. * @param string|array $validate 验证器名或者验证规则数组
  130. * @param array $message 提示信息
  131. * @param bool $batch 是否批量验证
  132. * @return array|string|true
  133. * @throws ValidateException
  134. */
  135. protected function validate(array $data, $validate, array $message = [], bool $batch = false)
  136. {
  137. if (is_array($validate)) {
  138. $v = new Validate();
  139. $v->rule($validate);
  140. } else {
  141. if (strpos($validate, '.')) {
  142. // 支持场景
  143. list($validate, $scene) = explode('.', $validate);
  144. }
  145. $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
  146. $v = new $class();
  147. if (!empty($scene)) {
  148. $v->scene($scene);
  149. }
  150. }
  151. $v->message($message);
  152. //是否批量验证
  153. if ($batch || $this->batchValidate) {
  154. $v->batch(true);
  155. }
  156. $result = $v->failException(false)->check($data);
  157. if (true !== $result) {
  158. return $v->getError();
  159. } else {
  160. return $result;
  161. }
  162. }
  163. /**
  164. * 操作成功跳转的快捷方法
  165. * @access protected
  166. * @param mixed $msg 提示信息
  167. * @param string $url 跳转的URL地址
  168. * @param mixed $data 返回的数据
  169. * @param integer $wait 跳转等待时间
  170. * @param array $header 发送的Header信息
  171. * @return void
  172. */
  173. protected function success($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
  174. {
  175. if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
  176. $url = $_SERVER["HTTP_REFERER"];
  177. } elseif ($url) {
  178. $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : (string)$this->app->route->buildUrl($url);
  179. }
  180. $result = [
  181. 'code' => 0,
  182. 'msg' => $msg,
  183. 'data' => $data,
  184. 'url' => $url,
  185. 'wait' => $wait,
  186. ];
  187. $type = $this->request->isJson() || $this->request->isAjax() ? 'json' : 'html';
  188. // 把跳转模板的渲染下沉,这样在 response_send 行为里通过getData()获得的数据是一致性的格式
  189. if ('html' == strtolower($type)) {
  190. $type = 'view';
  191. $response = Response::create($this->app->config->get('jump.dispatch_success_tmpl'), $type)->assign($result)->header($header);
  192. } else {
  193. $response = Response::create($result, $type)->header($header);
  194. }
  195. throw new HttpResponseException($response);
  196. }
  197. /**
  198. * 操作错误跳转的快捷方法
  199. * @access protected
  200. * @param mixed $msg 提示信息
  201. * @param string $url 跳转的URL地址
  202. * @param mixed $data 返回的数据
  203. * @param integer $wait 跳转等待时间
  204. * @param array $header 发送的Header信息
  205. * @return void
  206. */
  207. protected function error($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
  208. {
  209. if (is_null($url)) {
  210. $url = $this->request->isAjax() ? '' : 'javascript:history.back(-1);';
  211. } elseif ($url) {
  212. $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : (string)$this->app->route->buildUrl($url);
  213. }
  214. $result = [
  215. 'code' => 1,
  216. 'msg' => $msg,
  217. 'data' => $data,
  218. 'url' => $url,
  219. 'wait' => $wait,
  220. ];
  221. $type = $this->request->isJson() || $this->request->isAjax() ? 'json' : 'html';
  222. if ('html' == strtolower($type)) {
  223. $type = 'view';
  224. $response = Response::create($this->app->config->get('jump.dispatch_error_tmpl'), $type)->assign($result)->header($header);
  225. } else {
  226. $response = Response::create($result, $type)->header($header);
  227. }
  228. throw new HttpResponseException($response);
  229. }
  230. // /**
  231. // * 返回封装后的API数据到客户端
  232. // * @param mixed $data 要返回的数据
  233. // * @param integer $code 返回的code
  234. // * @param mixed $msg 提示信息
  235. // * @param string $type 返回数据格式
  236. // * @param array $header 发送的Header信息
  237. // * @return Response
  238. // */
  239. // protected function result($data, int $code = 0, $msg = '', string $type = '', array $header = []): Response
  240. // {
  241. // $result = [
  242. // 'code' => $code,
  243. // 'msg' => $msg,
  244. // 'time' => time(),
  245. // 'data' => $data,
  246. // ];
  247. // $type = $type ?: 'json';
  248. // $response = Response::create($result, $type)->header($header);
  249. // throw new HttpResponseException($response);
  250. // }
  251. // // 列表
  252. // public function index()
  253. // {
  254. // // 获取主键
  255. // $pk = MakeBuilder::getPrimarykey($this->tableName);
  256. // // 获取列表数据
  257. // $columns = MakeBuilder::getListColumns($this->tableName);
  258. // // 获取搜索数据
  259. // $search = MakeBuilder::getListSearch($this->tableName);
  260. // // 获取当前模块信息
  261. // $model = '\app\model\\' . $this->modelName;
  262. // $module = \app\model\Module::where('table_name', $this->tableName)->find();
  263. // // 搜索
  264. // if (Request::param('getList') == 1) {
  265. // $where = MakeBuilder::getListWhere($this->tableName);
  266. // $orderByColumn = Request::param('orderByColumn') ?? $pk;
  267. // $isAsc = Request::param('isAsc') ?? 'desc';
  268. // return $model::getList($where, $this->pageSize, [$orderByColumn => $isAsc]);
  269. // }
  270. // // 检测单页模式
  271. // $isSingle = MakeBuilder::checkSingle($this->modelName);
  272. // if ($isSingle) {
  273. // return $this->jump($isSingle);
  274. // }
  275. // // 获取新增地址
  276. // $addUlr = MakeBuilder::getAddUrl($this->tableName);
  277. // // 构建页面
  278. // return TableBuilder::getInstance()
  279. // ->setUniqueId($pk) // 设置主键
  280. // ->addColumns($columns) // 添加列表字段数据
  281. // ->setSearch($search) // 添加头部搜索
  282. // ->addColumn('right_button', '操作', 'btn') // 启用右侧操作列
  283. // ->addRightButtons($module->right_button) // 设置右侧操作列
  284. // ->addTopButtons($module->top_button) // 设置顶部按钮组
  285. // ->setAddUrl($addUlr) // 设置新增地址
  286. // ->fetch();
  287. // }
  288. /**
  289. * 新增 or 修改
  290. * @param int $id info id
  291. * @return mix
  292. */
  293. public function save($id = 0)
  294. {
  295. if ($this->app->request->isPost()) {
  296. $params = $this->app->request->param();
  297. try {
  298. $id = $params['id'];
  299. unset($params['id']);
  300. if ($id != 0) {
  301. $this->modelName::update($params, ['id' => $id]);
  302. } else {
  303. $this->modelName::create($params);
  304. }
  305. } catch (\Exception $e) {
  306. $msg = $e->getMessage();
  307. $this->error("错误提示:".$msg);
  308. }
  309. $this->success('操作成功', (String)url('index'));
  310. } else {
  311. if ($id != 0) {
  312. $data = $this->modelName::find($id);
  313. } else {
  314. $data = null;
  315. }
  316. View::assign('data', $data);
  317. return View::fetch();
  318. }
  319. }
  320. /**
  321. * 删除
  322. * @param int|array $id info id
  323. * @return array
  324. */
  325. public function delete($id)
  326. {
  327. if (Request::isPost()) {
  328. $model = '\app\model\\' . $this->modelName;
  329. if ($model ::destroy($id)) {
  330. return ['code' => 0,'msg'=>'删除成功'];
  331. } else {
  332. return ['code' => 1,'msg'=>'删除失败'];
  333. }
  334. }
  335. }
  336. // 排序
  337. public function sort()
  338. {
  339. if (Request::isPost()) {
  340. $param = Request::param();
  341. $model = '\app\model\\' . $this->modelName;
  342. return $model::sorts($param);
  343. }
  344. }
  345. // 状态变更
  346. public function status(int $id)
  347. {
  348. if (Request::isPost()) {
  349. $model = '\app\model\\' . $this->modelName;
  350. return $model::state($id);
  351. }
  352. }
  353. // // 导出
  354. // public function export()
  355. // {
  356. // \app\model\Base::export($this->tableName, $this->modelName);
  357. // }
  358. // 获取当前登录用户信息
  359. protected function getSysUser()
  360. {
  361. if (!$this->sysUser) {
  362. $this->sysUser = \app\model\SysUser::where('userid', session('adminuser.userid'))->find();
  363. }
  364. return $this->sysUser;
  365. }
  366. }