Files
2026-03-07 19:42:22 +08:00

80 lines
2.1 KiB
PHP
Raw Permalink 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
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';
}
}