| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247 |
- <?php
- namespace app\common\controller;
- use app\common\library\Auth;
- use think\Config;
- use think\exception\HttpResponseException;
- use think\exception\ValidateException;
- use think\Hook;
- use think\Lang;
- use think\Loader;
- use think\Paginator;
- use think\Request;
- use think\Response;
- use think\Route;
- use think\Validate;
- /**
- * API控制器基类
- */
- class Api
- {
- /**
- * @var Request Request 实例
- */
- protected $request;
- /**
- * @var array 前置操作方法列表
- */
- protected array $beforeActionList = [];
- /**
- * 无需登录的方法,同时也就不需要鉴权了
- * @var array
- */
- protected array $noNeedLogin = [];
- /**
- * 权限Auth
- * @var Auth
- */
- protected Auth $auth;
- /**
- * 默认响应输出类型,支持json/xml
- * @var string
- */
- protected string $responseType = 'json';
- /**
- * 每页条数
- * @var int
- */
- protected int $pageSize = 10;
- /**
- * 构造方法
- * @param Request|null $request
- */
- public function __construct(Request $request = null)
- {
- $this->request = is_null($request) ? Request::instance() : $request;
- // 控制器初始化
- $this->_initialize();
- // 前置操作方法
- if ($this->beforeActionList) {
- foreach ($this->beforeActionList as $method => $options) {
- is_numeric($method) ?
- $this->beforeAction($options) :
- $this->beforeAction($method, $options);
- }
- }
- }
- /**
- * 初始化操作
- * @access protected
- */
- protected function _initialize()
- {
- //跨域请求检测
- check_cors_request();
- // 检测IP是否允许
- check_ip_allowed();
- //移除HTML标签
- $this->request->filter('trim,strip_tags,htmlspecialchars');
- $this->auth = Auth::instance();
- $controllername = Loader::parseName($this->request->controller());
- $actionname = strtolower($this->request->action());
- // 请求头里的加密过的token
- $token = $this->request->header("Token", "");
- $path = str_replace('.', '/', $controllername) . '/' . $actionname;
- // 设置当前请求的URI
- $this->auth->setRequestUri($path);
- // 检测是否需要验证登录
- if (!$this->auth->match($this->noNeedLogin)) {
- //初始化
- $this->auth->init($token);
- //检测是否登录
- if (!$this->auth->isLogin()) {
- $this->error(__('Please login first'), null,14999); // 未登录时,返回特定的code
- }
- }
- $upload = \app\common\model\Config::upload();
- // 上传信息配置后
- Hook::listen("upload_config_init", $upload);
- Config::set('upload', array_merge(Config::get('upload'), $upload));
- // 加载当前控制器语言包
- $this->loadlang($controllername);
- }
- /**
- * 加载语言文件
- * @param string $name
- */
- protected function loadlang($name)
- {
- $name = Loader::parseName($name);
- $name = preg_match("/^([a-zA-Z0-9_\.\/]+)\$/i", $name) ? $name : 'index';
- $lang = $this->request->langset();
- $lang = preg_match("/^([a-zA-Z\-_]{2,10})\$/i", $lang) ? $lang : 'zh-cn';
- Lang::load(APP_PATH . $this->request->module() . '/lang/' . $lang . '/' . str_replace('.', '/', $name) . '.php');
- }
- /**
- * 操作成功返回的数据
- * @param string $msg 提示信息
- * @param mixed $data 要返回的数据
- * @param int $code 错误码,默认为1
- * @param string|null $type 输出类型
- * @param array $header 发送的 Header 信息
- */
- protected function success(string $msg = '', $data = null, int $code = 200, string $type = null, array $header = [])
- {
- if (empty($msg)) {
- $msg = "操作成功";
- }
- $this->result($msg, $data, $code, $type, $header);
- }
- /**
- * 操作失败返回的数据
- * @param string $msg 提示信息
- * @param mixed $data 要返回的数据
- * @param int $code 错误码,默认为0
- * @param string|null $type 输出类型
- * @param array $header 发送的 Header 信息
- */
- protected function error(string $msg = '', $data = null, int $code = 15000, string $type = null, array $header = [])
- {
- if (empty($msg)) {
- $msg = "操作失败";
- }
- $this->result($msg, $data, $code, $type, $header);
- }
- /**
- * 返回封装后的 API 数据到客户端
- * @access protected
- * @param mixed $msg 提示信息
- * @param mixed $data 要返回的数据
- * @param int $code 错误码,默认为0
- * @param string|null $type 输出类型,支持json/xml/jsonp
- * @param array $header 发送的 Header 信息
- * @return void
- * @throws HttpResponseException
- */
- protected function result($msg, $data = null, int $code = 0, string $type = null, array $header = [])
- {
- $result = [
- 'code' => $code,
- 'msg' => $msg,
- 'time' => Request::instance()->server('REQUEST_TIME'),
- 'data' => $data,
- ];
- // 如果未设置类型则自动判断
- $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);
- if (isset($header['statuscode'])) {
- $code = $header['statuscode'];
- unset($header['statuscode']);
- } else {
- //未设置状态码,根据code值判断
- $code = $code >= 1000 || $code < 200 ? 200 : $code;
- }
- $response = Response::create($result, $type, $code)->header($header);
- throw new HttpResponseException($response);
- }
- /**
- * 前置操作
- * @access protected
- * @param string $method 前置操作方法名
- * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
- * @return void
- */
- protected function beforeAction(string $method, array $options = [])
- {
- if (isset($options['only'])) {
- if (is_string($options['only'])) {
- $options['only'] = explode(',', $options['only']);
- }
- if (!in_array($this->request->action(), $options['only'])) {
- return;
- }
- } elseif (isset($options['except'])) {
- if (is_string($options['except'])) {
- $options['except'] = explode(',', $options['except']);
- }
- if (in_array($this->request->action(), $options['except'])) {
- return;
- }
- }
- call_user_func([$this, $method]);
- }
- /**
- * 构造分页的相应
- * @param Paginator $paginator
- * @return array
- */
- protected function buildResp(int $total, int $currentPage, array $rows): array
- {
- return [
- 'total' => $total,
- 'current_page' => $currentPage,
- 'rows' => $rows,
- ];
- }
- }
|