Files
wh-api/app/Job/OpLogsJob.php
ykxiao 0b2299c427
Some checks failed
Build Docker / build (push) Has been cancelled
协程版仓库后端项目
2025-07-08 14:59:47 +08:00

88 lines
2.8 KiB
PHP
Executable File
Raw 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\Job;
use App\Constants\SourceConst;
use App\JsonRpc\EasyAppServiceInterface;
use App\Model\OperatorLogs;
use Exception;
use Hyperf\Collection\Collection;
use function Hyperf\Collection\collect;
use function Hyperf\Config\config;
use function Hyperf\Support\make;
/**
* Author: ykxiao
* Date: 2024/12/25
* Time: 上午9:36
* Description: 操作日志记录任务.
*
* (c) ykxiao <yk_9001@hotmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
class OpLogsJob extends BaseJob
{
/**
* 处理日志记录逻辑。
* 该方法首先尝试获取日志操作信息,如果信息不为空,则根据这些信息填充操作日志数组,
* 包括日志类型、标题、计时器以及来源信息。随后,它将尝试获取当前用户信息,并最后创建操作日志记录。
*
* @return void 该方法没有返回值。
* @throws Exception
*/
protected function process(): void
{
// 尝试获取日志操作信息
$logAction = $this->getLogAction();
// 如果日志操作信息为空,则直接返回,不进行后续操作
if ($logAction->isEmpty()) {
return;
}
$rpcResult = make(EasyAppServiceInterface::class)->getClientIPInfo(['ip' => $this->data['ip']]);
// 构建请求日志消息
$clientIPInfo = $rpcResult['result']['ip_info'] ?? '';
// 从日志操作信息中提取日志类型,并保存到操作日志数组中
$type = $logAction->first()['id'] ?? 0;
$this->data['type'] = $type;
// 同样从日志操作信息中提取日志标题,并保存
$this->data['log_title'] = $logAction->first()['name'] ?? '';
// 初始化计时器
$this->data['timer'] = 0;
// 设置日志来源,优先使用已存在的来源信息,如果不存在,则尝试从路由前缀获取来源信息
$this->data['source'] = $this->data['source'] ?: $this->getRoutePrefix();
// 查询IP属地并保存到操作日志数组中
$this->data['location'] = $clientIPInfo;
// 创建操作日志记录
OperatorLogs::query()->create($this->data);
}
private function getLogAction(): Collection
{
$defineLogs = config('op_logs');
return collect($defineLogs)->where('action', '=', $this->data['action']);
}
/**
* 获取路由前缀.
*/
private function getRoutePrefix(): int
{
$arr = explode('/', $this->data['route']);
$res = $arr[0] ?? '';
return match ($res) {
'api' => SourceConst::SOURCE_PC,
'mobile' => SourceConst::SOURCE_MOBILE,
default => 0,
};
}
}