招标
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

90 lines
2.3 KiB

<?php
namespace app\common\controller;
use app\BaseController;
use app\middleware\BeComplicatedBy;
use app\middleware\Token;
use think\event\LogWrite;
use think\facade\Event;
/**
* Class Api 接口基类
* @package app\common\controller
*/
class Api extends BaseController
{
/**
* @var array|string[] 控制器中间件
*/
public array $middleware = [Token::class, BeComplicatedBy::class ];
/**
* 初始化函数
*/
protected function initialize()
{
Event::listen(LogWrite::class, function ($event) {
$this->requestListen($event);
});
parent::initialize(); // TODO: Change the autogenerated stub
}
/**
* 验证数据并返回数据
* @param string $scene 场景值或验证器带场景值
* @example $this->validateGetData('add') | $this->validateGetData('\\app\\common\\validate\\User.add')
* @return array
*/
final public function validateGetData(string $scene)
{
$data = $this->request->post();
if (strpos($scene, '\\') !== false) {
$validateAndScene = $scene;
list($validate, $scene) = explode('.', $validateAndScene);
}else{
$validateClass = explode('\\', static::class);
$validateClass = array_pop($validateClass);
$validate = "\\app\\common\\validate\\{$validateClass}";
$validateAndScene = "{$validate}.{$scene}";
}
$this->validate($data, $validateAndScene);
$validateField = (fn() => ($this->scene[$scene] ?? []))->call(new $validate);
return data_only($data, $validateField);
}
/**
* 请求监听
* @param LogWrite $event
*/
private function requestListen(LogWrite $event)
{
if ($this->request->middleware('request_listen') !== true) {
unset($event->log['info'], $event->log['sql']);
return;
}
$info = $sql = [];
$end = '';
foreach ($event->log as $key => $value) {
if ($key === 'info') {
$end = array_pop($value);
$info = $value;
} else if($key === 'sql') {
$sql = $event->log['sql'];
}
}
$event->log['sql'] = [];
$event->log['info'] = ["\r\n" . implode("\r\n > ", array_merge($info, $sql)) . "\r\n" . $end];
}
}