Files
MBTI_wang/api/app/BaseController.php
卡若 ce55c48c64 feat: 同步今日小程序与后台迭代版本
集中提交今日 API、管理端、小程序与部署文档调整,确保 Gitea 主分支与本地最新开发版本一致。

Made-with: Cursor
2026-04-20 11:07:55 +08:00

142 lines
3.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app;
use think\App;
use think\exception\ValidateException;
use think\Validate;
use app\common\service\JwtService;
/**
* 控制器基础类
*/
abstract class BaseController
{
/**
* Request实例
* @var \think\Request
*/
protected $request;
/**
* 应用实例
* @var \think\App
*/
protected $app;
/**
* 是否批量验证
* @var bool
*/
protected $batchValidate = false;
/**
* 控制器中间件
* @var array
*/
protected $middleware = [];
/**
* 构造方法
* @access public
* @param App $app 应用对象
*/
public function __construct(App $app)
{
$this->app = $app;
$this->request = $this->app->request;
// 控制器初始化
$this->initialize();
}
// 初始化
protected function initialize()
{}
/**
* 验证数据
* @access protected
* @param array $data 数据
* @param string|array $validate 验证器名或者验证规则数组
* @param array $message 提示信息
* @param bool $batch 是否批量验证
* @return array|string|true
* @throws ValidateException
*/
/**
* 从请求中解析当前登录用户(兼容中间件注入和 JWT 直接解析两种方式)
*/
protected function resolveUser(): ?array
{
$user = $this->request->user ?? null;
if ($user) {
return is_array($user) ? $user : (array) $user;
}
$token = JwtService::getTokenFromRequest($this->request);
if (!$token) {
return null;
}
$payload = JwtService::verifyToken($token);
if (!$payload) {
return null;
}
return [
'source' => $payload['source'] ?? '',
'user_id' => $payload['user_id'] ?? $payload['userId'] ?? null,
'userId' => $payload['user_id'] ?? $payload['userId'] ?? null,
];
}
/**
* 当前请求 JWT 主体用户 id与 Auth 中间件一致user_id / userId兼容历史 id
*/
protected function jwtSubjectUserId(): int
{
$fromReq = $this->request->userId ?? null;
if ($fromReq !== null && $fromReq !== '') {
$n = (int) $fromReq;
if ($n > 0) {
return $n;
}
}
$user = $this->request->user ?? [];
if (!is_array($user)) {
return 0;
}
return (int) ($user['user_id'] ?? $user['userId'] ?? $user['id'] ?? 0);
}
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, '.')) {
// 支持场景
[$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);
}
return $v->failException(true)->check($data);
}
}