fix: resolve PHPStan static analysis warnings

This commit is contained in:
xboard
2025-04-14 02:12:42 +08:00
parent 3d254c02c1
commit 2d3e4b4a95
84 changed files with 2330 additions and 1190 deletions

View File

@@ -112,16 +112,13 @@ class CheckCommission extends Command
DB::rollBack();
return false;
}
if (!CommissionLog::create([
CommissionLog::create([
'invite_user_id' => $inviteUserId,
'user_id' => $order->user_id,
'trade_no' => $order->trade_no,
'order_amount' => $order->total_amount,
'get_amount' => $commissionBalance
])) {
DB::rollBack();
return false;
}
]);
$inviteUserId = $inviter->invite_user_id;
// update order actual commission balance
$order->actual_commission_balance = $order->actual_commission_balance + $commissionBalance;

View File

@@ -19,11 +19,11 @@ class ExportV2Log extends Command
public function handle()
{
$days = $this->argument('days');
$date = Carbon::now()->subDays($days)->startOfDay();
$date = Carbon::now()->subDays((float) $days)->startOfDay();
$logs = DB::table('v2_log')
->where('created_at', '>=', $date->timestamp)
->get();
->where('created_at', '>=', $date->timestamp)
->get();
$fileName = "v2_logs_" . Carbon::now()->format('Y_m_d_His') . ".csv";
$handle = fopen(storage_path("logs/$fileName"), 'w');
@@ -35,19 +35,19 @@ class ExportV2Log extends Command
fputcsv($handle, [
$log->level,
$log->id,
$log->title,
$log->host,
$log->uri,
$log->method,
$log->data,
$log->ip,
$log->context,
Carbon::createFromTimestamp($log->created_at)->toDateTimeString(),
$log->title,
$log->host,
$log->uri,
$log->method,
$log->data,
$log->ip,
$log->context,
Carbon::createFromTimestamp($log->created_at)->toDateTimeString(),
Carbon::createFromTimestamp($log->updated_at)->toDateTimeString()
]);
}
fclose($handle);
$this->info("日志成功导出到: ". storage_path("logs/$fileName"));
$this->info("日志成功导出到: " . storage_path("logs/$fileName"));
}
}

View File

@@ -5,30 +5,26 @@ namespace App\Console\Commands;
use App\Models\Plan;
use Illuminate\Console\Command;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
class ResetTraffic extends Command
{
protected $builder;
/**
* The name and signature of the console command.
*
* @var Builder
*/
protected $builder;
/**
* @var string
*/
protected $signature = 'reset:traffic';
/**
* The console command description.
*
* @var string
*/
protected $description = '流量清空';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
@@ -37,13 +33,13 @@ class ResetTraffic extends Command
}
/**
* Execute the console command.
*
* @return mixed
* 执行流量重置命令
*/
public function handle()
{
ini_set('memory_limit', -1);
// 按重置方法分组查询所有套餐
$resetMethods = Plan::select(
DB::raw("GROUP_CONCAT(`id`) as plan_ids"),
DB::raw("reset_traffic_method as method")
@@ -51,138 +47,117 @@ class ResetTraffic extends Command
->groupBy('reset_traffic_method')
->get()
->toArray();
// 使用闭包直接引用方法
$resetHandlers = [
Plan::RESET_TRAFFIC_FIRST_DAY_MONTH => fn($builder) => $this->resetByMonthFirstDay($builder),
Plan::RESET_TRAFFIC_MONTHLY => fn($builder) => $this->resetByExpireDay($builder),
Plan::RESET_TRAFFIC_NEVER => null,
Plan::RESET_TRAFFIC_FIRST_DAY_YEAR => fn($builder) => $this->resetByYearFirstDay($builder),
Plan::RESET_TRAFFIC_YEARLY => fn($builder) => $this->resetByExpireYear($builder),
];
// 处理每种重置方法
foreach ($resetMethods as $resetMethod) {
$planIds = explode(',', $resetMethod['plan_ids']);
switch (true) {
case ($resetMethod['method'] === NULL): {
$resetTrafficMethod = admin_setting('reset_traffic_method', 0);
$builder = with(clone ($this->builder))->whereIn('plan_id', $planIds);
switch ((int) $resetTrafficMethod) {
// month first day
case 0:
$this->resetByMonthFirstDay($builder);
break;
// expire day
case 1:
$this->resetByExpireDay($builder);
break;
// no action
case 2:
break;
// year first day
case 3:
$this->resetByYearFirstDay($builder);
// year expire day
case 4:
$this->resetByExpireYear($builder);
}
break;
}
case ($resetMethod['method'] === 0): {
$builder = with(clone ($this->builder))->whereIn('plan_id', $planIds);
$this->resetByMonthFirstDay($builder);
break;
}
case ($resetMethod['method'] === 1): {
$builder = with(clone ($this->builder))->whereIn('plan_id', $planIds);
$this->resetByExpireDay($builder);
break;
}
case ($resetMethod['method'] === 2): {
break;
}
case ($resetMethod['method'] === 3): {
$builder = with(clone ($this->builder))->whereIn('plan_id', $planIds);
$this->resetByYearFirstDay($builder);
break;
}
case ($resetMethod['method'] === 4): {
$builder = with(clone ($this->builder))->whereIn('plan_id', $planIds);
$this->resetByExpireYear($builder);
break;
}
// 获取重置方法
$method = $resetMethod['method'];
if ($method === NULL) {
$method = (int) admin_setting('reset_traffic_method', 0);
}
// 跳过不重置的方法
if ($method === 2) {
continue;
}
// 获取该方法的处理器
$handler = $resetHandlers[$method] ?? null;
if (!$handler) {
continue;
}
// 创建查询构建器并执行重置
$userQuery = (clone $this->builder)->whereIn('plan_id', $planIds);
$handler($userQuery);
}
}
private function resetByExpireYear($builder): void
/**
* 按用户年度到期日重置流量
*/
private function resetByExpireYear(Builder $builder): void
{
$users = $builder->with('plan')->get();
$usersToUpdate = [];
foreach ($users as $user) {
$expireDay = date('m-d', $user->expired_at);
$today = date('m-d');
if ($expireDay === $today) {
$usersToUpdate[] = [
'id' => $user->id,
'transfer_enable' => $user->plan->transfer_enable
];
}
}
foreach ($usersToUpdate as $userData) {
User::where('id', $userData['id'])->update([
'transfer_enable' => (intval($userData['transfer_enable']) * 1073741824),
'u' => 0,
'd' => 0
]);
}
$today = date('m-d');
$this->resetUsersByDateCondition($builder, function ($user) use ($today) {
return date('m-d', $user->expired_at) === $today;
});
}
private function resetByYearFirstDay($builder): void
/**
* 按新年第一天重置流量
*/
private function resetByYearFirstDay(Builder $builder): void
{
$users = $builder->with('plan')->get();
$usersToUpdate = [];
foreach ($users as $user) {
if ((string) date('md') === '0101') {
$usersToUpdate[] = [
'id' => $user->id,
'transfer_enable' => $user->plan->transfer_enable
];
}
$isNewYear = date('md') === '0101';
if (!$isNewYear) {
return;
}
foreach ($usersToUpdate as $userData) {
User::where('id', $userData['id'])->update([
'transfer_enable' => (intval($userData['transfer_enable']) * 1073741824),
'u' => 0,
'd' => 0
]);
}
$this->resetAllUsers($builder);
}
private function resetByMonthFirstDay($builder): void
/**
* 按月初第一天重置流量
*/
private function resetByMonthFirstDay(Builder $builder): void
{
$users = $builder->with('plan')->get();
$usersToUpdate = [];
foreach ($users as $user) {
if ((string) date('d') === '01') {
$usersToUpdate[] = [
'id' => $user->id,
'transfer_enable' => $user->plan->transfer_enable
];
}
$isFirstDayOfMonth = date('d') === '01';
if (!$isFirstDayOfMonth) {
return;
}
foreach ($usersToUpdate as $userData) {
User::where('id', $userData['id'])->update([
'transfer_enable' => (intval($userData['transfer_enable']) * 1073741824),
'u' => 0,
'd' => 0
]);
}
$this->resetAllUsers($builder);
}
private function resetByExpireDay($builder): void
/**
* 按用户到期日重置流量
*/
private function resetByExpireDay(Builder $builder): void
{
$lastDay = date('d', strtotime('last day of +0 months'));
$today = date('d');
$lastDay = date('d', strtotime('last day of +0 months'));
$this->resetUsersByDateCondition($builder, function ($user) use ($today, $lastDay) {
$expireDay = date('d', $user->expired_at);
return $expireDay === $today || ($today === $lastDay && $expireDay >= $today);
});
}
/**
* 重置所有符合条件的用户流量
*/
private function resetAllUsers(Builder $builder): void
{
$this->resetUsersByDateCondition($builder, function () {
return true;
});
}
/**
* 根据日期条件重置用户流量
* @param Builder $builder 用户查询构建器
* @param callable $condition 日期条件回调
*/
private function resetUsersByDateCondition(Builder $builder, callable $condition): void
{
/** @var \App\Models\User[] $users */
$users = $builder->with('plan')->get();
$usersToUpdate = [];
foreach ($users as $user) {
$expireDay = date('d', $user->expired_at);
if ($expireDay === $today || ($today === $lastDay && $expireDay >= $today)) {
if ($condition($user)) {
$usersToUpdate[] = [
'id' => $user->id,
'transfer_enable' => $user->plan->transfer_enable

View File

@@ -50,9 +50,9 @@ class XboardInstall extends Command
{
try {
$isDocker = file_exists('/.dockerenv');
$enableSqlite = env('ENABLE_SQLITE', false);
$enableRedis = env('ENABLE_REDIS', false);
$adminAccount = env('ADMIN_ACCOUNT', '');
$enableSqlite = getenv('ENABLE_SQLITE', false);
$enableRedis = getenv('ENABLE_REDIS', false);
$adminAccount = getenv('ADMIN_ACCOUNT', false);
$this->info("__ __ ____ _ ");
$this->info("\ \ / /| __ ) ___ __ _ _ __ __| | ");
$this->info(" \ \/ / | __ \ / _ \ / _` | '__/ _` | ");
@@ -60,7 +60,7 @@ class XboardInstall extends Command
$this->info("/_/ \_\|____/ \___/ \__,_|_| \__,_| ");
if (
(File::exists(base_path() . '/.env') && $this->getEnvValue('INSTALLED'))
|| (env('INSTALLED', false) && $isDocker)
|| (getenv('INSTALLED', false) && $isDocker)
) {
$securePath = admin_setting('secure_path', admin_setting('frontend_admin_path', hash('crc32b', config('app.key'))));
$this->info("访问 http(s)://你的站点/{$securePath} 进入管理面板,你可以在用户中心修改你的密码。");

View File

@@ -2,12 +2,10 @@
namespace App\Console\Commands;
use App\Models\StatServer;
use App\Models\StatUser;
use App\Services\StatisticalService;
use Illuminate\Console\Command;
use App\Models\Stat;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class XboardStatistics extends Command
{
@@ -50,67 +48,6 @@ class XboardStatistics extends Command
info('统计任务执行完毕。耗时:' . (microtime(true) - $startAt) / 1000);
}
private function statServer()
{
try {
DB::beginTransaction();
$createdAt = time();
$recordAt = strtotime('-1 day', strtotime(date('Y-m-d')));
$statService = new StatisticalService();
$statService->setStartAt($recordAt);
$stats = $statService->getStatServer();
foreach ($stats as $stat) {
if (!StatServer::insert([
'server_id' => $stat['server_id'],
'server_type' => $stat['server_type'],
'u' => $stat['u'],
'd' => $stat['d'],
'created_at' => $createdAt,
'updated_at' => $createdAt,
'record_type' => 'd',
'record_at' => $recordAt
])) {
throw new \Exception('stat server fail');
}
}
DB::commit();
$statService->clearStatServer();
} catch (\Exception $e) {
DB::rollback();
\Log::error($e->getMessage(), ['exception' => $e]);
}
}
private function statUser()
{
try {
DB::beginTransaction();
$createdAt = time();
$recordAt = strtotime('-1 day', strtotime(date('Y-m-d')));
$statService = new StatisticalService();
$statService->setStartAt($recordAt);
$stats = $statService->getStatUser();
foreach ($stats as $stat) {
if (!StatUser::insert([
'user_id' => $stat['user_id'],
'u' => $stat['u'],
'd' => $stat['d'],
'server_rate' => $stat['server_rate'],
'created_at' => $createdAt,
'updated_at' => $createdAt,
'record_type' => 'd',
'record_at' => $recordAt
])) {
throw new \Exception('stat user fail');
}
}
DB::commit();
$statService->clearStatUser();
} catch (\Exception $e) {
DB::rollback();
\Log::error($e->getMessage(), ['exception' => $e]);
}
}
private function stat()
{
@@ -132,7 +69,7 @@ class XboardStatistics extends Command
}
Stat::create($data);
} catch (\Exception $e) {
\Log::error($e->getMessage(), ['exception' => $e]);
Log::error($e->getMessage(), ['exception' => $e]);
}
}
}

View File

@@ -42,9 +42,9 @@ class Kernel extends ConsoleKernel
// horizon metrics
$schedule->command('horizon:snapshot')->everyFiveMinutes()->onOneServer();
// backup Timing
if (env('ENABLE_AUTO_BACKUP_AND_UPDATE', false)) {
$schedule->command('backup:database', ['true'])->daily()->onOneServer();
}
// if (env('ENABLE_AUTO_BACKUP_AND_UPDATE', false)) {
// $schedule->command('backup:database', ['true'])->daily()->onOneServer();
// }
// 每分钟清理过期的在线状态
$schedule->call(function () {
app(UserOnlineService::class)->cleanExpiredOnlineStatus();