From 2c3246ebf66ad0777766ec4c160b22f92320d97d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A6=99=E7=A0=81=E7=94=9F=E8=8A=B1?= <18523774412@qq.com> Date: Sat, 24 Jun 2023 02:04:44 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=E5=AE=8C=E5=96=84=E5=9F=BA=E7=B1=BB?= =?UTF-8?q?=E7=9A=84=E7=B1=BB=E5=9E=8B=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/BaseController.php | 33 ++++++------ app/admin/library/traits/Backend.php | 59 ++++++++++---------- app/common/controller/Api.php | 19 ++++--- app/common/controller/Backend.php | 81 +++++++++++++++++++--------- app/common/controller/Frontend.php | 18 +++++-- 5 files changed, 124 insertions(+), 86 deletions(-) diff --git a/app/BaseController.php b/app/BaseController.php index 1ec73525..7be50b19 100644 --- a/app/BaseController.php +++ b/app/BaseController.php @@ -4,8 +4,9 @@ declare (strict_types=1); namespace app; use think\App; -use think\exception\ValidateException; +use think\Request; use think\Validate; +use think\exception\ValidateException; /** * 控制器基础类 @@ -14,36 +15,29 @@ abstract class BaseController { /** * Request实例 - * @var \think\Request + * @var Request */ - protected $request; - - /** - * 应用实例 - * @var App - */ - protected $app; + protected Request $request; /** * 是否批量验证 * @var bool */ - protected $batchValidate = false; + protected bool $batchValidate = false; /** * 控制器中间件 * @var array */ - protected $middleware = []; + protected array $middleware = []; /** * 构造方法 * @access public * @param App $app 应用对象 */ - public function __construct(App $app) + public function __construct(protected App $app) { - $this->app = $app; $this->request = $this->app->request; $this->request->controllerPath = str_replace('.', '/', $this->request->controller(true)); @@ -51,8 +45,11 @@ abstract class BaseController $this->initialize(); } - // 初始化 - protected function initialize() + /** + * 初始化 + * @access protected + */ + protected function initialize(): void { } @@ -60,13 +57,13 @@ abstract class BaseController * 验证数据 * @access protected * @param array $data 数据 - * @param string|array $validate 验证器名或者验证规则数组 + * @param array|string $validate 验证器名或者验证规则数组 * @param array $message 提示信息 * @param bool $batch 是否批量验证 * @return array|string|true * @throws ValidateException */ - protected function validate(array $data, $validate, array $message = [], bool $batch = false) + protected function validate(array $data, array|string $validate, array $message = [], bool $batch = false): bool|array|string { if (is_array($validate)) { $v = new Validate(); @@ -76,7 +73,7 @@ abstract class BaseController // 支持场景 [$validate, $scene] = explode('.', $validate); } - $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate); + $class = str_contains($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate); $v = new $class(); if (!empty($scene)) { $v->scene($scene); diff --git a/app/admin/library/traits/Backend.php b/app/admin/library/traits/Backend.php index 8f0db05c..8cff6529 100644 --- a/app/admin/library/traits/Backend.php +++ b/app/admin/library/traits/Backend.php @@ -2,25 +2,23 @@ namespace app\admin\library\traits; -use Exception; -use think\facade\Config; +use Throwable; use think\facade\Db; -use think\db\exception\PDOException; -use think\exception\ValidateException; +use think\facade\Config; /** * 后台控制器trait类 - * 已导入到 @var \app\common\controller\Backend 中 + * 已导入到 @see \app\common\controller\Backend 中 * 若需修改此类方法:请复制方法至对应控制器后进行重写 */ trait Backend { /** * 排除入库字段 - * @param $params - * @return mixed + * @param array $params + * @return array */ - protected function excludeFields($params) + protected function excludeFields(array $params): array { if (!is_array($this->preExcludeFields)) { $this->preExcludeFields = explode(',', (string)$this->preExcludeFields); @@ -36,8 +34,9 @@ trait Backend /** * 查看 + * @throws Throwable */ - public function index() + public function index(): void { $this->request->filter(['strip_tags', 'trim']); if ($this->request->param('select')) { @@ -63,7 +62,7 @@ trait Backend /** * 添加 */ - public function add() + public function add(): void { if ($this->request->isPost()) { $data = $this->request->post(); @@ -77,7 +76,7 @@ trait Backend } $result = false; - Db::startTrans(); + $this->model->startTrans(); try { // 模型验证 if ($this->modelValidate) { @@ -89,9 +88,9 @@ trait Backend } } $result = $this->model->save($data); - Db::commit(); - } catch (ValidateException|PDOException|Exception $e) { - Db::rollback(); + $this->model->commit(); + } catch (Throwable $e) { + $this->model->rollback(); $this->error($e->getMessage()); } if ($result !== false) { @@ -106,8 +105,9 @@ trait Backend /** * 编辑 + * @throws Throwable */ - public function edit() + public function edit(): void { $id = $this->request->param($this->model->getPk()); $row = $this->model->find($id); @@ -128,7 +128,7 @@ trait Backend $data = $this->excludeFields($data); $result = false; - Db::startTrans(); + $this->model->startTrans(); try { // 模型验证 if ($this->modelValidate) { @@ -140,9 +140,9 @@ trait Backend } } $result = $row->save($data); - Db::commit(); - } catch (ValidateException|PDOException|Exception $e) { - Db::rollback(); + $this->model->commit(); + } catch (Throwable $e) { + $this->model->rollback(); $this->error($e->getMessage()); } if ($result !== false) { @@ -150,7 +150,6 @@ trait Backend } else { $this->error(__('No rows updated')); } - } $this->success('', [ @@ -161,8 +160,9 @@ trait Backend /** * 删除 * @param array $ids + * @throws Throwable */ - public function del(array $ids = []) + public function del(array $ids = []): void { if (!$this->request->isDelete() || !$ids) { $this->error(__('Parameter error')); @@ -176,14 +176,14 @@ trait Backend $pk = $this->model->getPk(); $data = $this->model->where($pk, 'in', $ids)->select(); $count = 0; - Db::startTrans(); + $this->model->startTrans(); try { foreach ($data as $v) { $count += $v->delete(); } - Db::commit(); - } catch (PDOException|Exception $e) { - Db::rollback(); + $this->model->commit(); + } catch (Throwable $e) { + $this->model->rollback(); $this->error($e->getMessage()); } if ($count) { @@ -197,8 +197,9 @@ trait Backend * 排序 * @param int $id 排序主键值 * @param int $targetId 排序位置主键值 + * @throws Throwable */ - public function sortable(int $id, int $targetId) + public function sortable(int $id, int $targetId): void { $dataLimitAdminIds = $this->getDataLimitAdminIds(); if ($dataLimitAdminIds) { @@ -229,9 +230,9 @@ trait Backend $target = $this->model->find($targetId); } - $ebak = $target[$this->weighField]; + $backup = $target[$this->weighField]; $target[$this->weighField] = $row[$this->weighField]; - $row[$this->weighField] = $ebak; + $row[$this->weighField] = $backup; $row->save(); $target->save(); @@ -242,7 +243,7 @@ trait Backend * 加载为select(远程下拉选择框)数据,默认还是走$this->index()方法 * 必要时请在对应控制器类中重写 */ - public function select() + public function select(): void { } diff --git a/app/common/controller/Api.php b/app/common/controller/Api.php index 2ff8fcf6..e920573b 100644 --- a/app/common/controller/Api.php +++ b/app/common/controller/Api.php @@ -18,13 +18,13 @@ class Api extends BaseController * 默认响应输出类型,支持json/xml/jsonp * @var string */ - protected $responseType = 'json'; + protected string $responseType = 'json'; /** * 应用站点系统设置 * @var bool */ - protected $useSystemSettings = true; + protected bool $useSystemSettings = true; public function __construct(App $app) { @@ -33,8 +33,9 @@ class Api extends BaseController /** * 控制器初始化方法 + * @access protected */ - protected function initialize() + protected function initialize(): void { if ($this->useSystemSettings) { // ip检查 @@ -46,12 +47,14 @@ class Api extends BaseController } parent::initialize(); + + // 设置默认过滤规则 $this->request->filter('trim,strip_tags,htmlspecialchars'); // 加载控制器语言包 - $langset = $this->app->lang->getLangSet(); + $langSet = $this->app->lang->getLangSet(); $this->app->lang->load([ - app_path() . 'lang' . DIRECTORY_SEPARATOR . $langset . DIRECTORY_SEPARATOR . (str_replace('/', DIRECTORY_SEPARATOR, $this->app->request->controllerPath)) . '.php' + app_path() . 'lang' . DIRECTORY_SEPARATOR . $langSet . DIRECTORY_SEPARATOR . (str_replace('/', DIRECTORY_SEPARATOR, $this->app->request->controllerPath)) . '.php' ]); } @@ -64,7 +67,7 @@ class Api extends BaseController * @param array $header 发送的 header 信息 * @param array $options Response 输出参数 */ - protected function success(string $msg = '', $data = null, int $code = 1, string $type = null, array $header = [], array $options = []) + protected function success(string $msg = '', mixed $data = null, int $code = 1, string $type = null, array $header = [], array $options = []) { $this->result($msg, $data, $code, $type, $header, $options); } @@ -78,7 +81,7 @@ class Api extends BaseController * @param array $header 发送的 header 信息 * @param array $options Response 输出参数 */ - protected function error(string $msg = '', $data = null, int $code = 0, string $type = null, array $header = [], array $options = []) + protected function error(string $msg = '', mixed $data = null, int $code = 0, string $type = null, array $header = [], array $options = []) { $this->result($msg, $data, $code, $type, $header, $options); } @@ -92,7 +95,7 @@ class Api extends BaseController * @param array $header 发送的 header 信息 * @param array $options Response 输出参数 */ - public function result(string $msg, $data = null, int $code = 0, string $type = null, array $header = [], array $options = []) + public function result(string $msg, mixed $data = null, int $code = 0, string $type = null, array $header = [], array $options = []) { $result = [ 'code' => $code, diff --git a/app/common/controller/Backend.php b/app/common/controller/Backend.php index 1a1376c5..c190726b 100644 --- a/app/common/controller/Backend.php +++ b/app/common/controller/Backend.php @@ -2,81 +2,97 @@ namespace app\common\controller; +use Throwable; +use think\Model; +use think\facade\Db; +use think\facade\Event; +use think\facade\Cookie; use app\admin\library\Auth; use think\db\exception\PDOException; use think\exception\HttpResponseException; -use think\facade\Cookie; -use think\facade\Db; -use think\facade\Event; class Backend extends Api { /** - * 无需登录的方法 - * 访问本控制器的此方法,无需管理员登录 + * 无需登录的方法,访问本控制器的此方法,无需管理员登录 + * @var array */ - protected $noNeedLogin = []; + protected array $noNeedLogin = []; /** * 无需鉴权的方法 + * @var array */ - protected $noNeedPermission = []; + protected array $noNeedPermission = []; /** * 新增/编辑时,对前端发送的字段进行排除(忽略不入库) + * @var array|string */ - protected $preExcludeFields = []; + protected array|string $preExcludeFields = []; /** * 权限类实例 * @var Auth */ - protected $auth = null; + protected Auth $auth; - protected $model = null; + /** + * 模型类实例 + * @var object + * @phpstan-var Model + */ + protected object $model; /** * 权重字段 + * @var string */ - protected $weighField = 'weigh'; + protected string $weighField = 'weigh'; /** * 默认排序 + * @var string|array */ - protected $defaultSortField = 'id,desc'; + protected string|array $defaultSortField = 'id,desc'; /** * 表格拖拽排序时,两个权重相等则自动重新整理 * config/buildadmin.php文件中的auto_sort_eq_weight为默认值 * null=取默认值,false=关,true=开 + * @var null|bool */ - protected $autoSortEqWeight = null; + protected null|bool $autoSortEqWeight = null; /** * 快速搜索字段 + * @var string|array */ - protected $quickSearchField = 'id'; + protected string|array $quickSearchField = 'id'; /** * 是否开启模型验证 + * @var bool */ - protected $modelValidate = true; + protected bool $modelValidate = true; /** * 是否开启模型场景验证 + * @var bool */ - protected $modelSceneValidate = false; + protected bool $modelSceneValidate = false; /** - * 关联查询方法名 - * 方法应定义在模型中 + * 关联查询方法名,方法应定义在模型中 + * @var array */ - protected $withJoinTable = []; + protected array $withJoinTable = []; /** * 关联查询JOIN方式 + * @var string */ - protected $withJoinType = 'LEFT'; + protected string $withJoinType = 'LEFT'; /** * 开启数据限制 @@ -87,23 +103,27 @@ class Backend extends Api * parent=上级分组中的管理员可查 * 指定分组中的管理员可查,比如 $dataLimit = 2; * 启用请确保数据表内存在 admin_id 字段,可以查询/编辑数据的管理员为admin_id对应的管理员+数据限制所表示的管理员们 + * @var bool|string|int */ - protected $dataLimit = false; + protected bool|string|int $dataLimit = false; /** * 数据限制字段 + * @var string */ - protected $dataLimitField = 'admin_id'; + protected string $dataLimitField = 'admin_id'; /** * 数据限制开启时自动填充字段值为当前管理员id + * @var bool */ - protected $dataLimitFieldAutoFill = true; + protected bool $dataLimitFieldAutoFill = true; /** * 查看请求返回的主表字段控制 + * @var string|array */ - protected $indexField = ['*']; + protected string|array $indexField = ['*']; /** * 引入traits @@ -111,7 +131,12 @@ class Backend extends Api */ use \app\admin\library\traits\Backend; - public function initialize() + /** + * 初始化 + * @throws Throwable + * @throws PDOException + */ + public function initialize(): void { parent::initialize(); @@ -140,7 +165,7 @@ class Backend extends Api } elseif ($token) { try { $this->auth->init($token); - } catch (HttpResponseException $e) { + } catch (HttpResponseException) { } } @@ -291,6 +316,10 @@ class Backend extends Api return [$where, $alias, $limit, $order]; } + /** + * 数据权限控制-获取有权限访问的管理员Ids + * @throws Throwable + */ protected function getDataLimitAdminIds(): array { if (!$this->dataLimit || $this->auth->isSuperAdmin()) { diff --git a/app/common/controller/Frontend.php b/app/common/controller/Frontend.php index ddbbc624..36e6e657 100644 --- a/app/common/controller/Frontend.php +++ b/app/common/controller/Frontend.php @@ -2,6 +2,7 @@ namespace app\common\controller; +use Throwable; use think\facade\Event; use think\facade\Cookie; use app\common\library\Auth; @@ -12,21 +13,28 @@ class Frontend extends Api /** * 无需登录的方法 * 访问本控制器的此方法,无需会员登录 + * @var array */ - protected $noNeedLogin = []; + protected array $noNeedLogin = []; /** * 无需鉴权的方法 + * @var array */ - protected $noNeedPermission = []; + protected array $noNeedPermission = []; /** * 权限类实例 * @var Auth */ - protected $auth = null; + protected Auth $auth; - public function initialize() + /** + * 初始化 + * @throws Throwable + * @throws HttpResponseException + */ + public function initialize(): void { parent::initialize(); $this->auth = Auth::instance(); @@ -47,7 +55,7 @@ class Frontend extends Api } elseif ($token) { try { $this->auth->init($token); - } catch (HttpResponseException $e) { + } catch (HttpResponseException) { } }