Base.php 13 KB

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