refactor:完善基类的类型定义

This commit is contained in:
妙码生花 2023-06-24 02:04:44 +08:00
parent 9eb7e84445
commit 2c3246ebf6
5 changed files with 124 additions and 86 deletions

View File

@ -4,8 +4,9 @@ declare (strict_types=1);
namespace app; namespace app;
use think\App; use think\App;
use think\exception\ValidateException; use think\Request;
use think\Validate; use think\Validate;
use think\exception\ValidateException;
/** /**
* 控制器基础类 * 控制器基础类
@ -14,36 +15,29 @@ abstract class BaseController
{ {
/** /**
* Request实例 * Request实例
* @var \think\Request * @var Request
*/ */
protected $request; protected Request $request;
/**
* 应用实例
* @var App
*/
protected $app;
/** /**
* 是否批量验证 * 是否批量验证
* @var bool * @var bool
*/ */
protected $batchValidate = false; protected bool $batchValidate = false;
/** /**
* 控制器中间件 * 控制器中间件
* @var array * @var array
*/ */
protected $middleware = []; protected array $middleware = [];
/** /**
* 构造方法 * 构造方法
* @access public * @access public
* @param App $app 应用对象 * @param App $app 应用对象
*/ */
public function __construct(App $app) public function __construct(protected App $app)
{ {
$this->app = $app;
$this->request = $this->app->request; $this->request = $this->app->request;
$this->request->controllerPath = str_replace('.', '/', $this->request->controller(true)); $this->request->controllerPath = str_replace('.', '/', $this->request->controller(true));
@ -51,8 +45,11 @@ abstract class BaseController
$this->initialize(); $this->initialize();
} }
// 初始化 /**
protected function initialize() * 初始化
* @access protected
*/
protected function initialize(): void
{ {
} }
@ -60,13 +57,13 @@ abstract class BaseController
* 验证数据 * 验证数据
* @access protected * @access protected
* @param array $data 数据 * @param array $data 数据
* @param string|array $validate 验证器名或者验证规则数组 * @param array|string $validate 验证器名或者验证规则数组
* @param array $message 提示信息 * @param array $message 提示信息
* @param bool $batch 是否批量验证 * @param bool $batch 是否批量验证
* @return array|string|true * @return array|string|true
* @throws ValidateException * @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)) { if (is_array($validate)) {
$v = new Validate(); $v = new Validate();
@ -76,7 +73,7 @@ abstract class BaseController
// 支持场景 // 支持场景
[$validate, $scene] = explode('.', $validate); [$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(); $v = new $class();
if (!empty($scene)) { if (!empty($scene)) {
$v->scene($scene); $v->scene($scene);

View File

@ -2,25 +2,23 @@
namespace app\admin\library\traits; namespace app\admin\library\traits;
use Exception; use Throwable;
use think\facade\Config;
use think\facade\Db; use think\facade\Db;
use think\db\exception\PDOException; use think\facade\Config;
use think\exception\ValidateException;
/** /**
* 后台控制器trait类 * 后台控制器trait类
* 已导入到 @var \app\common\controller\Backend * 已导入到 @see \app\common\controller\Backend
* 若需修改此类方法:请复制方法至对应控制器后进行重写 * 若需修改此类方法:请复制方法至对应控制器后进行重写
*/ */
trait Backend trait Backend
{ {
/** /**
* 排除入库字段 * 排除入库字段
* @param $params * @param array $params
* @return mixed * @return array
*/ */
protected function excludeFields($params) protected function excludeFields(array $params): array
{ {
if (!is_array($this->preExcludeFields)) { if (!is_array($this->preExcludeFields)) {
$this->preExcludeFields = explode(',', (string)$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']); $this->request->filter(['strip_tags', 'trim']);
if ($this->request->param('select')) { if ($this->request->param('select')) {
@ -63,7 +62,7 @@ trait Backend
/** /**
* 添加 * 添加
*/ */
public function add() public function add(): void
{ {
if ($this->request->isPost()) { if ($this->request->isPost()) {
$data = $this->request->post(); $data = $this->request->post();
@ -77,7 +76,7 @@ trait Backend
} }
$result = false; $result = false;
Db::startTrans(); $this->model->startTrans();
try { try {
// 模型验证 // 模型验证
if ($this->modelValidate) { if ($this->modelValidate) {
@ -89,9 +88,9 @@ trait Backend
} }
} }
$result = $this->model->save($data); $result = $this->model->save($data);
Db::commit(); $this->model->commit();
} catch (ValidateException|PDOException|Exception $e) { } catch (Throwable $e) {
Db::rollback(); $this->model->rollback();
$this->error($e->getMessage()); $this->error($e->getMessage());
} }
if ($result !== false) { 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()); $id = $this->request->param($this->model->getPk());
$row = $this->model->find($id); $row = $this->model->find($id);
@ -128,7 +128,7 @@ trait Backend
$data = $this->excludeFields($data); $data = $this->excludeFields($data);
$result = false; $result = false;
Db::startTrans(); $this->model->startTrans();
try { try {
// 模型验证 // 模型验证
if ($this->modelValidate) { if ($this->modelValidate) {
@ -140,9 +140,9 @@ trait Backend
} }
} }
$result = $row->save($data); $result = $row->save($data);
Db::commit(); $this->model->commit();
} catch (ValidateException|PDOException|Exception $e) { } catch (Throwable $e) {
Db::rollback(); $this->model->rollback();
$this->error($e->getMessage()); $this->error($e->getMessage());
} }
if ($result !== false) { if ($result !== false) {
@ -150,7 +150,6 @@ trait Backend
} else { } else {
$this->error(__('No rows updated')); $this->error(__('No rows updated'));
} }
} }
$this->success('', [ $this->success('', [
@ -161,8 +160,9 @@ trait Backend
/** /**
* 删除 * 删除
* @param array $ids * @param array $ids
* @throws Throwable
*/ */
public function del(array $ids = []) public function del(array $ids = []): void
{ {
if (!$this->request->isDelete() || !$ids) { if (!$this->request->isDelete() || !$ids) {
$this->error(__('Parameter error')); $this->error(__('Parameter error'));
@ -176,14 +176,14 @@ trait Backend
$pk = $this->model->getPk(); $pk = $this->model->getPk();
$data = $this->model->where($pk, 'in', $ids)->select(); $data = $this->model->where($pk, 'in', $ids)->select();
$count = 0; $count = 0;
Db::startTrans(); $this->model->startTrans();
try { try {
foreach ($data as $v) { foreach ($data as $v) {
$count += $v->delete(); $count += $v->delete();
} }
Db::commit(); $this->model->commit();
} catch (PDOException|Exception $e) { } catch (Throwable $e) {
Db::rollback(); $this->model->rollback();
$this->error($e->getMessage()); $this->error($e->getMessage());
} }
if ($count) { if ($count) {
@ -197,8 +197,9 @@ trait Backend
* 排序 * 排序
* @param int $id 排序主键值 * @param int $id 排序主键值
* @param int $targetId 排序位置主键值 * @param int $targetId 排序位置主键值
* @throws Throwable
*/ */
public function sortable(int $id, int $targetId) public function sortable(int $id, int $targetId): void
{ {
$dataLimitAdminIds = $this->getDataLimitAdminIds(); $dataLimitAdminIds = $this->getDataLimitAdminIds();
if ($dataLimitAdminIds) { if ($dataLimitAdminIds) {
@ -229,9 +230,9 @@ trait Backend
$target = $this->model->find($targetId); $target = $this->model->find($targetId);
} }
$ebak = $target[$this->weighField]; $backup = $target[$this->weighField];
$target[$this->weighField] = $row[$this->weighField]; $target[$this->weighField] = $row[$this->weighField];
$row[$this->weighField] = $ebak; $row[$this->weighField] = $backup;
$row->save(); $row->save();
$target->save(); $target->save();
@ -242,7 +243,7 @@ trait Backend
* 加载为select(远程下拉选择框)数据,默认还是走$this->index()方法 * 加载为select(远程下拉选择框)数据,默认还是走$this->index()方法
* 必要时请在对应控制器类中重写 * 必要时请在对应控制器类中重写
*/ */
public function select() public function select(): void
{ {
} }

View File

@ -18,13 +18,13 @@ class Api extends BaseController
* 默认响应输出类型,支持json/xml/jsonp * 默认响应输出类型,支持json/xml/jsonp
* @var string * @var string
*/ */
protected $responseType = 'json'; protected string $responseType = 'json';
/** /**
* 应用站点系统设置 * 应用站点系统设置
* @var bool * @var bool
*/ */
protected $useSystemSettings = true; protected bool $useSystemSettings = true;
public function __construct(App $app) 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) { if ($this->useSystemSettings) {
// ip检查 // ip检查
@ -46,12 +47,14 @@ class Api extends BaseController
} }
parent::initialize(); parent::initialize();
// 设置默认过滤规则
$this->request->filter('trim,strip_tags,htmlspecialchars'); $this->request->filter('trim,strip_tags,htmlspecialchars');
// 加载控制器语言包 // 加载控制器语言包
$langset = $this->app->lang->getLangSet(); $langSet = $this->app->lang->getLangSet();
$this->app->lang->load([ $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 $header 发送的 header 信息
* @param array $options Response 输出参数 * @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); $this->result($msg, $data, $code, $type, $header, $options);
} }
@ -78,7 +81,7 @@ class Api extends BaseController
* @param array $header 发送的 header 信息 * @param array $header 发送的 header 信息
* @param array $options Response 输出参数 * @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); $this->result($msg, $data, $code, $type, $header, $options);
} }
@ -92,7 +95,7 @@ class Api extends BaseController
* @param array $header 发送的 header 信息 * @param array $header 发送的 header 信息
* @param array $options Response 输出参数 * @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 = [ $result = [
'code' => $code, 'code' => $code,

View File

@ -2,81 +2,97 @@
namespace app\common\controller; 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 app\admin\library\Auth;
use think\db\exception\PDOException; use think\db\exception\PDOException;
use think\exception\HttpResponseException; use think\exception\HttpResponseException;
use think\facade\Cookie;
use think\facade\Db;
use think\facade\Event;
class Backend extends Api 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 * @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为默认值 * config/buildadmin.php文件中的auto_sort_eq_weight为默认值
* null=取默认值,false=,true= * 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方式 * 关联查询JOIN方式
* @var string
*/ */
protected $withJoinType = 'LEFT'; protected string $withJoinType = 'LEFT';
/** /**
* 开启数据限制 * 开启数据限制
@ -87,23 +103,27 @@ class Backend extends Api
* parent=上级分组中的管理员可查 * parent=上级分组中的管理员可查
* 指定分组中的管理员可查,比如 $dataLimit = 2; * 指定分组中的管理员可查,比如 $dataLimit = 2;
* 启用请确保数据表内存在 admin_id 字段,可以查询/编辑数据的管理员为admin_id对应的管理员+数据限制所表示的管理员们 * 启用请确保数据表内存在 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 * 数据限制开启时自动填充字段值为当前管理员id
* @var bool
*/ */
protected $dataLimitFieldAutoFill = true; protected bool $dataLimitFieldAutoFill = true;
/** /**
* 查看请求返回的主表字段控制 * 查看请求返回的主表字段控制
* @var string|array
*/ */
protected $indexField = ['*']; protected string|array $indexField = ['*'];
/** /**
* 引入traits * 引入traits
@ -111,7 +131,12 @@ class Backend extends Api
*/ */
use \app\admin\library\traits\Backend; use \app\admin\library\traits\Backend;
public function initialize() /**
* 初始化
* @throws Throwable
* @throws PDOException
*/
public function initialize(): void
{ {
parent::initialize(); parent::initialize();
@ -140,7 +165,7 @@ class Backend extends Api
} elseif ($token) { } elseif ($token) {
try { try {
$this->auth->init($token); $this->auth->init($token);
} catch (HttpResponseException $e) { } catch (HttpResponseException) {
} }
} }
@ -291,6 +316,10 @@ class Backend extends Api
return [$where, $alias, $limit, $order]; return [$where, $alias, $limit, $order];
} }
/**
* 数据权限控制-获取有权限访问的管理员Ids
* @throws Throwable
*/
protected function getDataLimitAdminIds(): array protected function getDataLimitAdminIds(): array
{ {
if (!$this->dataLimit || $this->auth->isSuperAdmin()) { if (!$this->dataLimit || $this->auth->isSuperAdmin()) {

View File

@ -2,6 +2,7 @@
namespace app\common\controller; namespace app\common\controller;
use Throwable;
use think\facade\Event; use think\facade\Event;
use think\facade\Cookie; use think\facade\Cookie;
use app\common\library\Auth; 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 * @var Auth
*/ */
protected $auth = null; protected Auth $auth;
public function initialize() /**
* 初始化
* @throws Throwable
* @throws HttpResponseException
*/
public function initialize(): void
{ {
parent::initialize(); parent::initialize();
$this->auth = Auth::instance(); $this->auth = Auth::instance();
@ -47,7 +55,7 @@ class Frontend extends Api
} elseif ($token) { } elseif ($token) {
try { try {
$this->auth->init($token); $this->auth->init($token);
} catch (HttpResponseException $e) { } catch (HttpResponseException) {
} }
} }