80 lines
2.1 KiB
PHP
80 lines
2.1 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace app\common\controller;
|
||
|
||
use app\support\BaseController;
|
||
use support\Response;
|
||
use support\think\Db;
|
||
use think\db\exception\PDOException;
|
||
use Webman\Http\Request as WebmanRequest;
|
||
|
||
/**
|
||
* API 控制器基类
|
||
* 迁移自 app/common/controller/Api.php,适配 Webman
|
||
*/
|
||
class Api extends BaseController
|
||
{
|
||
/**
|
||
* 默认响应输出类型
|
||
*/
|
||
protected string $responseType = 'json';
|
||
|
||
/**
|
||
* 是否开启系统站点配置(数据库检查、ip_check、set_timezone)
|
||
*/
|
||
protected bool $useSystemSettings = true;
|
||
|
||
/**
|
||
* API 初始化(需在控制器方法开头调用)
|
||
* @param WebmanRequest $request
|
||
* @return Response|null 若需直接返回(如 ip 禁止、数据库错误)则返回 Response,否则 null
|
||
*/
|
||
public function initializeApi(WebmanRequest $request): ?Response
|
||
{
|
||
$this->setRequest($request);
|
||
|
||
if ($this->useSystemSettings) {
|
||
// 检查数据库连接
|
||
try {
|
||
Db::execute('SELECT 1');
|
||
} catch (PDOException $e) {
|
||
return $this->error(mb_convert_encoding($e->getMessage(), 'UTF-8', 'UTF-8,GBK,GB2312,BIG5'));
|
||
}
|
||
|
||
// IP 检查
|
||
$ipCheckResponse = ip_check(null, $request);
|
||
if ($ipCheckResponse !== null) {
|
||
return $ipCheckResponse;
|
||
}
|
||
|
||
// 时区设定
|
||
set_timezone();
|
||
}
|
||
|
||
// 语言包由 LoadLangPack 中间件加载
|
||
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 从 Request 或路由解析控制器路径(如 user/user)
|
||
* 优先从 $request->controller 解析,否则从 path 解析
|
||
*/
|
||
protected function getControllerPath(WebmanRequest $request): ?string
|
||
{
|
||
return get_controller_path($request);
|
||
}
|
||
|
||
/**
|
||
* 从 Request 解析应用名(api 或 admin)
|
||
*/
|
||
protected function getAppFromRequest(WebmanRequest $request): string
|
||
{
|
||
$path = trim($request->path(), '/');
|
||
$parts = explode('/', $path);
|
||
return $parts[0] ?? 'api';
|
||
}
|
||
}
|