123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420 |
- <?php
- /**
- * +----------------------------------------------------------------------
- * | 基础控制器
- * +----------------------------------------------------------------------
- * AUTHOR: huwhois
- * EMAIL: huwhois@163.com
- * DATETIME: 2020/03/08
- */
- declare(strict_types=1);
- namespace app\sys\controller;
- // 引入框架内置类
- use think\App;
- use think\exception\HttpResponseException;
- use think\exception\ValidateException;
- use think\facade\Config;
- use think\facade\Request;
- use think\facade\Session;
- use think\facade\View;
- use think\Response;
- use think\Validate;
- use app\common\model\SysMenu;
- /**
- * 控制器基础类
- */
- abstract class Base
- {
- // use \liliuwei\think\Jump;
- /**
- * Request实例
- * @var \think\Request
- */
- protected $request;
- /**
- * 应用实例
- * @var \think\App
- */
- protected $app;
- /**
- * 是否批量验证
- * @var bool
- */
- protected $batchValidate = false;
- /**
- * 控制器中间件
- * @var array
- */
- protected $middleware = ['app\sys\middleware\Admin'];
- // /**
- // * 分页数量
- // * @var int
- // */
- // protected $pageSize = 0;
- /**
- * 系统设置
- * @var array
- */
- protected $system = [];
- /**
- * 用户信息
- */
- protected $sysUser;
- protected $modelName;
- /**
- * 构造方法
- * @access public
- * @param App $app 应用对象
- */
- public function __construct(App $app)
- {
- $this->app = $app;
- $this->request = $this->app->request;
- // 控制器初始化
- $this->initialize();
- }
- // 初始化
- protected function initialize()
- {
- // 左侧菜单
- $rid = Session::get('adminuser.roleid');
- $menus = $rid !=null ? SysMenu::getUserMenuList($rid) : [];
- $controller = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', Request::controller()));
- $action = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', Request::action()));
- $route = $controller . '/' . $action;
-
- $breadCrumb = SysMenu::getBreadCrumb($route);
- // layer open
- if (Request::has('_layer')) {
- View::assign('layer', true);
- } else {
- View::assign('layer', false);
- }
- // // pjax
- // if (Request::has('_pjax')) {
- // View::assign(['pjax' => true]);
- // } else {
- // View::assign(['pjax' => false]);
- // }
- // 内容管理,获取栏目列表
- // if (class_exists('\app\common\model\Cate')) {
- // $cates = \app\common\model\Cate::getList();
- // }
- // View::assign(['cates' => unlimitedForLayer($cates['data'] ?? [])]);
- // index应用地址
- // $domainBind = Config::get('app.domain_bind');
- // if ($domainBind) {
- // $domainBindKey = array_search('index', $domainBind);
- // $domainBindKey = $domainBindKey == '*' ? 'www.' : ($domainBindKey ? $domainBindKey . '.' : '');
- // $indexUrl = Request::scheme() . '://' . $domainBindKey . Request::rootDomain() . '/';
- // }
- // View::assign(['indexUrl' => $indexUrl ?? '/']);
- // 查询系统设置
- $system = \app\common\model\System::find(1);
- $this->system = $system;
- View::assign([
- 'active_pid' => $breadCrumb['active_pid'],
- 'breadCrumb' => $breadCrumb['breadCrumb'],
- 'menus' => $menus,
- 'system' => $system,
- 'sys_version' => Config::get('app.sys_version'),
- 'default_lang' => env('lang.default_lang', 'en')
- ]);
- }
- /**
- * 验证数据
- * @access protected
- * @param array $data 数据
- * @param string|array $validate 验证器名或者验证规则数组
- * @param array $message 提示信息
- * @param bool $batch 是否批量验证
- * @return array|string|true
- * @throws ValidateException
- */
- protected function validate(array $data, $validate, array $message = [], bool $batch = false)
- {
- if (is_array($validate)) {
- $v = new Validate();
- $v->rule($validate);
- } else {
- if (strpos($validate, '.')) {
- // 支持场景
- list($validate, $scene) = explode('.', $validate);
- }
- $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
- $v = new $class();
- if (!empty($scene)) {
- $v->scene($scene);
- }
- }
- $v->message($message);
- //是否批量验证
- if ($batch || $this->batchValidate) {
- $v->batch(true);
- }
- $result = $v->failException(false)->check($data);
- if (true !== $result) {
- return $v->getError();
- } else {
- return $result;
- }
- }
- /**
- * 操作成功跳转的快捷方法
- * @access protected
- * @param mixed $msg 提示信息
- * @param string $url 跳转的URL地址
- * @param mixed $data 返回的数据
- * @param integer $wait 跳转等待时间
- * @param array $header 发送的Header信息
- * @return void
- */
- protected function success($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
- {
- if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
- $url = $_SERVER["HTTP_REFERER"];
- } elseif ($url) {
- $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : (string)$this->app->route->buildUrl($url);
- }
- $result = [
- 'code' => 0,
- 'msg' => $msg,
- 'data' => $data,
- 'url' => $url,
- 'wait' => $wait,
- ];
- $type = $this->request->isJson() || $this->request->isAjax() ? 'json' : 'html';
- // 把跳转模板的渲染下沉,这样在 response_send 行为里通过getData()获得的数据是一致性的格式
- if ('html' == strtolower($type)) {
- $type = 'view';
- $response = Response::create($this->app->config->get('jump.dispatch_success_tmpl'), $type)->assign($result)->header($header);
- } else {
- $response = Response::create($result, $type)->header($header);
- }
- throw new HttpResponseException($response);
- }
- /**
- * 操作错误跳转的快捷方法
- * @access protected
- * @param mixed $msg 提示信息
- * @param string $url 跳转的URL地址
- * @param mixed $data 返回的数据
- * @param integer $wait 跳转等待时间
- * @param array $header 发送的Header信息
- * @return void
- */
- protected function error($msg = '', string $url = null, $data = '', int $wait = 3, array $header = [])
- {
- if (is_null($url)) {
- $url = $this->request->isAjax() ? '' : 'javascript:history.back(-1);';
- } elseif ($url) {
- $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : (string)$this->app->route->buildUrl($url);
- }
- $result = [
- 'code' => 1,
- 'msg' => $msg,
- 'data' => $data,
- 'url' => $url,
- 'wait' => $wait,
- ];
- $type = $this->request->isJson() || $this->request->isAjax() ? 'json' : 'html';
- if ('html' == strtolower($type)) {
- $type = 'view';
- $response = Response::create($this->app->config->get('jump.dispatch_error_tmpl'), $type)->assign($result)->header($header);
- } else {
- $response = Response::create($result, $type)->header($header);
- }
- throw new HttpResponseException($response);
- }
- // /**
- // * 返回封装后的API数据到客户端
- // * @param mixed $data 要返回的数据
- // * @param integer $code 返回的code
- // * @param mixed $msg 提示信息
- // * @param string $type 返回数据格式
- // * @param array $header 发送的Header信息
- // * @return Response
- // */
- // protected function result($data, int $code = 0, $msg = '', string $type = '', array $header = []): Response
- // {
- // $result = [
- // 'code' => $code,
- // 'msg' => $msg,
- // 'time' => time(),
- // 'data' => $data,
- // ];
- // $type = $type ?: 'json';
- // $response = Response::create($result, $type)->header($header);
- // throw new HttpResponseException($response);
- // }
- // // 列表
- // public function index()
- // {
- // // 获取主键
- // $pk = MakeBuilder::getPrimarykey($this->tableName);
- // // 获取列表数据
- // $columns = MakeBuilder::getListColumns($this->tableName);
- // // 获取搜索数据
- // $search = MakeBuilder::getListSearch($this->tableName);
- // // 获取当前模块信息
- // $model = '\app\common\model\\' . $this->modelName;
- // $module = \app\common\model\Module::where('table_name', $this->tableName)->find();
- // // 搜索
- // if (Request::param('getList') == 1) {
- // $where = MakeBuilder::getListWhere($this->tableName);
- // $orderByColumn = Request::param('orderByColumn') ?? $pk;
- // $isAsc = Request::param('isAsc') ?? 'desc';
- // return $model::getList($where, $this->pageSize, [$orderByColumn => $isAsc]);
- // }
- // // 检测单页模式
- // $isSingle = MakeBuilder::checkSingle($this->modelName);
- // if ($isSingle) {
- // return $this->jump($isSingle);
- // }
- // // 获取新增地址
- // $addUlr = MakeBuilder::getAddUrl($this->tableName);
- // // 构建页面
- // return TableBuilder::getInstance()
- // ->setUniqueId($pk) // 设置主键
- // ->addColumns($columns) // 添加列表字段数据
- // ->setSearch($search) // 添加头部搜索
- // ->addColumn('right_button', '操作', 'btn') // 启用右侧操作列
- // ->addRightButtons($module->right_button) // 设置右侧操作列
- // ->addTopButtons($module->top_button) // 设置顶部按钮组
- // ->setAddUrl($addUlr) // 设置新增地址
- // ->fetch();
- // }
- /**
- * 新增 or 修改
- * @param int $id info id
- * @return mix
- */
- public function save($id = 0)
- {
- if ($this->app->request->isPost()) {
- $params = $this->app->request->param();
- try {
- $id = $params['id'];
- unset($params['id']);
- if ($id != 0) {
- $this->modelName::update($params, ['id' => $id]);
- } else {
- $this->modelName::create($params);
- }
- } catch (\Exception $e) {
- $msg = $e->getMessage();
- $this->error("错误提示:".$msg);
- }
- $this->success('操作成功', (String)url('index'));
- } else {
- if ($id != 0) {
- $data = $this->modelName::find($id);
- } else {
- $data = null;
- }
-
- View::assign('data', $data);
- return View::fetch();
- }
- }
- /**
- * 删除
- * @param int|array $id info id
- * @return array
- */
- public function delete($id)
- {
- if (Request::isPost()) {
- $model = '\app\common\model\\' . $this->modelName;
- if ($model ::destroy($id)) {
- return ['code' => 0,'msg'=>'删除成功'];
- } else {
- return ['code' => 1,'msg'=>'删除失败'];
- }
- }
- }
- // 排序
- public function sort()
- {
- if (Request::isPost()) {
- $param = Request::param();
- $model = '\app\common\model\\' . $this->modelName;
- return $model::sorts($param);
- }
- }
- // 状态变更
- public function status(int $id)
- {
- if (Request::isPost()) {
- $model = '\app\common\model\\' . $this->modelName;
- return $model::state($id);
- }
- }
- // // 导出
- // public function export()
- // {
- // \app\common\model\Base::export($this->tableName, $this->modelName);
- // }
- // 获取当前登录用户信息
- protected function getSysUser()
- {
- if (!$this->sysUser) {
- $this->sysUser = \app\common\model\SysUser::where('userid', session('adminuser.userid'))->find();
- }
- return $this->sysUser;
- }
- }
|