Base.php 13 KB

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