Base.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. /**
  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\sys\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. /**
  64. * 构造方法
  65. * @access public
  66. * @param App $app 应用对象
  67. */
  68. public function __construct(App $app)
  69. {
  70. $this->app = $app;
  71. $this->request = $this->app->request;
  72. // 控制器初始化
  73. $this->initialize();
  74. }
  75. // 初始化
  76. protected function initialize()
  77. {
  78. // 左侧菜单
  79. $rid = Session::get('adminuser.roleid');
  80. $menus = Cache::get('menus');
  81. if (!$menus) {
  82. $menus = \app\common\model\SysMenu::getUserMenuList($rid);
  83. Cache::set('menus', $menus);
  84. }
  85. $controller = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', Request::controller()));
  86. $action = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', Request::action()));
  87. $route = $controller . '/' . $action;
  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. // 当前活动菜单父id & 面包导航
  101. $this->getBreadCrumb($route);
  102. $menus = obj_tree($menus);
  103. View::assign('menus', $menus);
  104. // 内容管理,获取栏目列表
  105. // if (class_exists('\app\common\model\Cate')) {
  106. // $cates = \app\common\model\Cate::getList();
  107. // }
  108. // View::assign(['cates' => unlimitedForLayer($cates['data'] ?? [])]);
  109. // index应用地址
  110. // $domainBind = Config::get('app.domain_bind');
  111. // if ($domainBind) {
  112. // $domainBindKey = array_search('index', $domainBind);
  113. // $domainBindKey = $domainBindKey == '*' ? 'www.' : ($domainBindKey ? $domainBindKey . '.' : '');
  114. // $indexUrl = Request::scheme() . '://' . $domainBindKey . Request::rootDomain() . '/';
  115. // }
  116. // View::assign(['indexUrl' => $indexUrl ?? '/']);
  117. // 查询系统设置
  118. // $system = \app\common\model\System::find(1);
  119. // $this->system = $system;
  120. View::assign([
  121. // 'system' => $system,
  122. 'sys_version' => Config::get('app.sys_version'),
  123. 'default_lang' => env('lang.default_lang', 'en')
  124. ]);
  125. }
  126. /**
  127. * 当前活动菜单父id & 面包导航
  128. */
  129. public function getBreadCrumb($route)
  130. {
  131. $active = \app\common\model\SysMenu::where('url', $route)->find();
  132. $active_pid = 0;
  133. $breadCrumb = [];
  134. if ($active) {
  135. $active_pid = $active->pid;
  136. $result = \app\common\model\SysMenu::find($active_pid);
  137. // 如果还有上级
  138. if ($result) {
  139. $res = \app\common\model\SysMenu::find($result->pid);
  140. // 如果还有上级
  141. if ($res) {
  142. $active_pid = $result->pid;
  143. $breadCrumb[] = [
  144. 'url' => $res['url'],
  145. 'title' => $res['name'],
  146. ];
  147. }
  148. $breadCrumb[] = [
  149. 'url' => $result['url'],
  150. 'title' => $result['name'],
  151. ];
  152. }
  153. $breadCrumb[] = [
  154. 'url' => $active['url'],
  155. 'title' => $active['name'],
  156. ];
  157. } else {
  158. $breadCrumb[] = [
  159. 'url' => null,
  160. 'title' => '我的桌面',
  161. ];
  162. }
  163. View::assign('active_pid', $active_pid);
  164. View::assign(['breadCrumb' => $breadCrumb]);
  165. }
  166. /**
  167. * 验证数据
  168. * @access protected
  169. * @param array $data 数据
  170. * @param string|array $validate 验证器名或者验证规则数组
  171. * @param array $message 提示信息
  172. * @param bool $batch 是否批量验证
  173. * @return array|string|true
  174. * @throws ValidateException
  175. */
  176. protected function validate(array $data, $validate, array $message = [], bool $batch = false)
  177. {
  178. if (is_array($validate)) {
  179. $v = new Validate();
  180. $v->rule($validate);
  181. } else {
  182. if (strpos($validate, '.')) {
  183. // 支持场景
  184. list($validate, $scene) = explode('.', $validate);
  185. }
  186. $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
  187. $v = new $class();
  188. if (!empty($scene)) {
  189. $v->scene($scene);
  190. }
  191. }
  192. $v->message($message);
  193. //是否批量验证
  194. if ($batch || $this->batchValidate) {
  195. $v->batch(true);
  196. }
  197. $result = $v->failException(false)->check($data);
  198. if (true !== $result) {
  199. return $v->getError();
  200. } else {
  201. return $result;
  202. }
  203. }
  204. // /**
  205. // * 返回封装后的API数据到客户端
  206. // * @param mixed $data 要返回的数据
  207. // * @param integer $code 返回的code
  208. // * @param mixed $msg 提示信息
  209. // * @param string $type 返回数据格式
  210. // * @param array $header 发送的Header信息
  211. // * @return Response
  212. // */
  213. // protected function result($data, int $code = 0, $msg = '', string $type = '', array $header = []): Response
  214. // {
  215. // $result = [
  216. // 'code' => $code,
  217. // 'msg' => $msg,
  218. // 'time' => time(),
  219. // 'data' => $data,
  220. // ];
  221. // $type = $type ?: 'json';
  222. // $response = Response::create($result, $type)->header($header);
  223. // throw new HttpResponseException($response);
  224. // }
  225. // // 列表
  226. // public function index()
  227. // {
  228. // // 获取主键
  229. // $pk = MakeBuilder::getPrimarykey($this->tableName);
  230. // // 获取列表数据
  231. // $columns = MakeBuilder::getListColumns($this->tableName);
  232. // // 获取搜索数据
  233. // $search = MakeBuilder::getListSearch($this->tableName);
  234. // // 获取当前模块信息
  235. // $model = '\app\common\model\\' . $this->modelName;
  236. // $module = \app\common\model\Module::where('table_name', $this->tableName)->find();
  237. // // 搜索
  238. // if (Request::param('getList') == 1) {
  239. // $where = MakeBuilder::getListWhere($this->tableName);
  240. // $orderByColumn = Request::param('orderByColumn') ?? $pk;
  241. // $isAsc = Request::param('isAsc') ?? 'desc';
  242. // return $model::getList($where, $this->pageSize, [$orderByColumn => $isAsc]);
  243. // }
  244. // // 检测单页模式
  245. // $isSingle = MakeBuilder::checkSingle($this->modelName);
  246. // if ($isSingle) {
  247. // return $this->jump($isSingle);
  248. // }
  249. // // 获取新增地址
  250. // $addUlr = MakeBuilder::getAddUrl($this->tableName);
  251. // // 构建页面
  252. // return TableBuilder::getInstance()
  253. // ->setUniqueId($pk) // 设置主键
  254. // ->addColumns($columns) // 添加列表字段数据
  255. // ->setSearch($search) // 添加头部搜索
  256. // ->addColumn('right_button', '操作', 'btn') // 启用右侧操作列
  257. // ->addRightButtons($module->right_button) // 设置右侧操作列
  258. // ->addTopButtons($module->top_button) // 设置顶部按钮组
  259. // ->setAddUrl($addUlr) // 设置新增地址
  260. // ->fetch();
  261. // }
  262. /**
  263. * 新增 or 修改
  264. * @param int $id info id
  265. * @return mix
  266. */
  267. public function save($id = 0)
  268. {
  269. if ($this->app->request->isPost()) {
  270. $params = $this->app->request->param();
  271. try {
  272. $id = $params['id'];
  273. unset($params['id']);
  274. if ($id != 0) {
  275. $this->modelName::update($params, ['id' => $id]);
  276. } else {
  277. $this->modelName::create($params);
  278. }
  279. } catch (\Exception $e) {
  280. $msg = $e->getMessage();
  281. $this->error("错误提示:".$msg);
  282. }
  283. $this->success('操作成功', (String)url('index'));
  284. } else {
  285. if ($id != 0) {
  286. $data = $this->modelName::find($id);
  287. } else {
  288. $data = null;
  289. }
  290. View::assign('data', $data);
  291. return View::fetch();
  292. }
  293. }
  294. /**
  295. * 删除
  296. * @param int|array $id info id
  297. * @return array
  298. */
  299. public function delete($id)
  300. {
  301. if (Request::isPost()) {
  302. if ($this->modelName::destroy($id)) {
  303. return ['code' => 1,'msg'=>'删除成功'];
  304. } else {
  305. return ['code' => 0,'msg'=>'删除失败'];
  306. }
  307. }
  308. }
  309. // 排序
  310. public function sort()
  311. {
  312. if (Request::isPost()) {
  313. $data = Request::post();
  314. return $this->modelName::sort($data);
  315. }
  316. }
  317. // 状态变更
  318. public function state(string $id)
  319. {
  320. if (Request::isPost()) {
  321. return $this->modelName::state($id);
  322. }
  323. }
  324. // // 导出
  325. // public function export()
  326. // {
  327. // \app\common\model\Base::export($this->tableName, $this->modelName);
  328. // }
  329. // 获取当前登录用户信息
  330. protected function getSysUser()
  331. {
  332. if (!$this->sysUser) {
  333. $this->sysUser = \app\common\model\SysUser::where('userid', session('adminuser.userid'))->find();
  334. }
  335. return $this->sysUser;
  336. }
  337. }