fastadmin/application/common/controller/Api.php

616 lines
18 KiB
PHP

<?php
namespace app\common\controller;
use app\common\library\Auth;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Lang;
use think\Loader;
use think\Request;
use think\Response;
/**
* API控制器基类
*/
class Api
{
/**
* @var Request Request 实例
*/
protected $request;
/**
* @var bool 验证失败是否抛出异常
*/
protected $failException = false;
/**
* @var bool 是否批量验证
*/
protected $batchValidate = false;
/**
* @var array 前置操作方法列表
*/
protected $beforeActionList = [];
/**
* 无需登录的方法,同时也就不需要鉴权了
* @var array
*/
protected $noNeedLogin = [];
/**
* 无需鉴权的方法,但需要登录
* @var array
*/
protected $noNeedRight = [];
/**
* 权限Auth
* @var Auth
*/
protected $auth = null;
// 项目添加 start
/**
* 快速搜索时执行查找的字段
*/
protected $searchFields = 'id';
/**
* 是否是关联查询
*/
protected $relationSearch = false;
/**
* 是否开启数据限制
* 支持auth/personal
* 表示按权限判断/仅限个人
* 默认为禁用,若启用请务必保证表中存在admin_id字段
*/
protected $dataLimit = false;
/**
* 数据限制字段
*/
protected $dataLimitField = 'admin_id';
/**
* 数据限制开启时自动填充限制字段值
*/
protected $dataLimitFieldAutoFill = true;
/**
* 是否开启Validate验证
*/
protected $modelValidate = false;
/**
* 是否开启模型场景验证
*/
protected $modelSceneValidate = false;
/**
* Multi方法可批量修改的字段
*/
protected $multiFields = 'status';
/**
* 导入文件首行类型
* 支持comment/name
* 表示注释或字段名
*/
protected $importHeadType = 'comment';
// 项目添加 end
/**
* 构造方法
* @access public
* @param Request $request 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()
{
$this->auth = Auth::instance();
$modulename = $this->request->module();
$controllername = strtolower($this->request->controller());
$actionname = strtolower($this->request->action());
// token
$token = $this->request->request('token') ?: $this->request->cookie('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'));
// }
// // 判断是否需要验证权限
// if (!$this->auth->match($this->noNeedRight))
// {
// // 判断控制器和方法判断是否有对应权限
// if (!$this->auth->check($path))
// {
// $this->error(__('You have no permission'));
// }
// }
// }
// else
// {
// // 如果有传递token才验证是否登录状态
// if ($token)
// {
// $this->auth->init($token);
// }
// }
// 加载当前控制器语言包
$this->loadlang($controllername);
}
/**
* 加载语言文件
* @param string $name
*/
protected function loadlang($name)
{
Lang::load(APP_PATH . $this->request->module() . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $name) . '.php');
}
/**
* 操作成功返回的数据
* @param string $msg 提示信息
* @param mixed $data 要返回的数据
* @param string $type 输出类型
* @param array $header 发送的 Header 信息
*/
protected function success($msg = '', $data = '', $type = 'json', array $header = [])
{
$this->result($data, 1, $msg, $type, $header);
}
/**
* 操作失败返回的数据
* @param string $msg 提示信息
* @param mixed $data 要返回的数据
* @param string $type 输出类型
* @param array $header 发送的 Header 信息
*/
protected function error($msg = '', $data = '', $type = 'json', array $header = [])
{
$this->result($data, 0, $msg, $type, $header);
}
/**
* 返回封装后的 API 数据到客户端
* @access protected
* @param mixed $data 要返回的数据
* @param int $code 返回的 code
* @param mixed $msg 提示信息
* @param string $type 返回数据格式
* @param array $header 发送的 Header 信息
* @return void
* @throws HttpResponseException
*/
protected function result($data, $code = 0, $msg = '', $type = '', array $header = [])
{
$result = [
'code' => $code,
'msg' => $msg,
'time' => Request::instance()->server('REQUEST_TIME'),
'data' => $data,
];
$type = $type ?: $this->getResponseType();
$response = Response::create($result, $type)->header($header);
throw new HttpResponseException($response);
}
/**
* 未找到请求的接口
*/
public function _empty()
{
return $this->error('Api not found');
}
/**
* 前置操作
* @access protected
* @param string $method 前置操作方法名
* @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
* @return void
*/
protected function beforeAction($method, $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]);
}
/**
* 设置验证失败后是否抛出异常
* @access protected
* @param bool $fail 是否抛出异常
* @return $this
*/
protected function validateFailException($fail = true)
{
$this->failException = $fail;
return $this;
}
/**
* 验证数据
* @access protected
* @param array $data 数据
* @param string|array $validate 验证器名或者验证规则数组
* @param array $message 提示信息
* @param bool $batch 是否批量验证
* @param mixed $callback 回调方法(闭包)
* @return array|string|true
* @throws ValidateException
*/
protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
{
if (is_array($validate))
{
$v = Loader::validate();
$v->rule($validate);
}
else
{
// 支持场景
if (strpos($validate, '.'))
{
list($validate, $scene) = explode('.', $validate);
}
$v = Loader::validate($validate);
!empty($scene) && $v->scene($scene);
}
// 批量验证
if ($batch || $this->batchValidate)
$v->batch(true);
// 设置错误信息
if (is_array($message))
$v->message($message);
// 使用回调验证
if ($callback && is_callable($callback))
{
call_user_func_array($callback, [$v, &$data]);
}
if (!$v->check($data))
{
if ($this->failException)
{
throw new ValidateException($v->getError());
}
return $v->getError();
}
return true;
}
// 项目添加
/**
* 生成查询所需要的条件,排序方式
* @param mixed $searchfields 快速查询的字段
* @param boolean $relationSearch 是否关联查询
* @return array
*/
protected function buildparams($searchfields = null, $relationSearch = null)
{
$searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
$relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
$search = $this->request->get("search", '');
$filter = $this->request->get("filter", '');
$op = $this->request->get("op", '', 'trim');
$sort = $this->request->get("sort", "id");
$order = $this->request->get("order", "DESC");
$offset = $this->request->get("offset", 0);
$limit = $this->request->get("limit", 0);
$filter = json_decode($filter, TRUE);
$op = json_decode($op, TRUE);
$filter = $filter ? $filter : [];
$where = [];
$tableName = '';
if ($relationSearch)
{
if (!empty($this->model))
{
$tableName = $this->model->getQuery()->getTable() . ".";
}
$sort = stripos($sort, ".") === false ? $tableName . $sort : $sort;
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds))
{
$where[] = [$tableName . $this->dataLimitField, 'in', $adminIds];
}
if ($search)
{
$searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
foreach ($searcharr as $k => &$v)
{
$v = stripos($v, ".") === false ? $tableName . $v : $v;
}
unset($v);
$where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
}
foreach ($filter as $k => $v)
{
$sym = isset($op[$k]) ? $op[$k] : '=';
if (stripos($k, ".") === false)
{
$k = $tableName . $k;
}
$sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
switch ($sym)
{
case '=':
case '!=':
$where[] = [$k, $sym, (string) $v];
break;
case 'LIKE':
case 'NOT LIKE':
case 'LIKE %...%':
case 'NOT LIKE %...%':
$where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
break;
case '>':
case '>=':
case '<':
case '<=':
$where[] = [$k, $sym, intval($v)];
break;
case 'IN':
case 'IN(...)':
case 'NOT IN':
case 'NOT IN(...)':
$where[] = [$k, str_replace('(...)', '', $sym), explode(',', $v)];
break;
case 'BETWEEN':
case 'NOT BETWEEN':
$arr = array_slice(explode(',', $v), 0, 2);
if (stripos($v, ',') === false || !array_filter($arr))
continue;
//当出现一边为空时改变操作符
if ($arr[0] === '')
{
$sym = $sym == 'BETWEEN' ? '<=' : '>';
$arr = $arr[1];
}
else if ($arr[1] === '')
{
$sym = $sym == 'BETWEEN' ? '>=' : '<';
$arr = $arr[0];
}
$where[] = [$k, $sym, $arr];
break;
case 'RANGE':
case 'NOT RANGE':
$v = str_replace(' - ', ',', $v);
$arr = array_slice(explode(',', $v), 0, 2);
if (stripos($v, ',') === false || !array_filter($arr))
continue;
//当出现一边为空时改变操作符
if ($arr[0] === '')
{
$sym = $sym == 'RANGE' ? '<=' : '>';
$arr = $arr[1];
}
else if ($arr[1] === '')
{
$sym = $sym == 'RANGE' ? '>=' : '<';
$arr = $arr[0];
}
$where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
break;
case 'LIKE':
case 'LIKE %...%':
$where[] = [$k, 'LIKE', "%{$v}%"];
break;
case 'NULL':
case 'IS NULL':
case 'NOT NULL':
case 'IS NOT NULL':
$where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
break;
default:
break;
}
}
$where = function($query) use ($where) {
foreach ($where as $k => $v)
{
if (is_array($v))
{
call_user_func_array([$query, 'where'], $v);
}
else
{
$query->where($v);
}
}
};
return [$where, $sort, $order, $offset, $limit];
}
/**
* 获取数据限制的管理员ID
* 禁用数据限制时返回的是null
* @return mixed
*/
protected function getDataLimitAdminIds()
{
if (!$this->dataLimit)
{
return null;
}
if ($this->auth->isSuperAdmin())
{
return null;
}
$adminIds = [];
if (in_array($this->dataLimit, ['auth', 'personal']))
{
$adminIds = $this->dataLimit == 'auth' ? $this->auth->getChildrenAdminIds(true) : [$this->auth->id];
}
return $adminIds;
}
/**
* Selectpage的实现方法
*
* 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
* 这里示例了所有的参数,所以比较复杂,实现上自己实现只需简单的几行即可
*
*/
protected function selectpage()
{
//设置过滤方法
$this->request->filter(['strip_tags', 'htmlspecialchars']);
//搜索关键词,客户端输入以空格分开,这里接收为数组
$word = (array) $this->request->request("q_word/a");
//当前页
$page = $this->request->request("page");
//分页大小
$pagesize = $this->request->request("per_page");
//搜索条件
$andor = $this->request->request("and_or");
//排序方式
$orderby = (array) $this->request->request("order_by/a");
//显示的字段
$field = $this->request->request("field");
//主键
$primarykey = $this->request->request("pkey_name");
//主键值
$primaryvalue = $this->request->request("pkey_value");
//搜索字段
$searchfield = (array) $this->request->request("search_field/a");
//自定义搜索条件
$custom = (array) $this->request->request("custom/a");
$order = [];
foreach ($orderby as $k => $v)
{
$order[$v[0]] = $v[1];
}
$field = $field ? $field : 'name';
//如果有primaryvalue,说明当前是初始化传值
if ($primaryvalue !== null)
{
$where = [$primarykey => ['in', $primaryvalue]];
}
else
{
$where = function($query) use($word, $andor, $field, $searchfield, $custom) {
foreach ($word as $k => $v)
{
foreach ($searchfield as $m => $n)
{
$query->where($n, "like", "%{$v}%", $andor);
}
}
if ($custom && is_array($custom))
{
foreach ($custom as $k => $v)
{
$query->where($k, '=', $v);
}
}
};
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds))
{
$this->model->where($this->dataLimitField, 'in', $adminIds);
}
$list = [];
$total = $this->model->where($where)->count();
if ($total > 0)
{
if (is_array($adminIds))
{
$this->model->where($this->dataLimitField, 'in', $adminIds);
}
$list = $this->model->where($where)
->order($order)
->page($page, $pagesize)
->field("{$primarykey},{$field}")
->field("password,salt", true)
->select();
}
//这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
return json(['list' => $list, 'total' => $total]);
}
}