CleanExpiredUserLogsCommand.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Module\Game\Commands;
  3. use App\Module\Game\Services\UserLogService;
  4. use UCore\Command\Command;
  5. /**
  6. * 清理过期用户日志命令
  7. */
  8. class CleanExpiredUserLogsCommand extends Command
  9. {
  10. /**
  11. * 命令名称和参数
  12. *
  13. * @var string
  14. */
  15. protected $signature = 'game:clean-expired-user-logs
  16. {--days=30 : 保留天数,默认30天}
  17. {--dry-run : 仅显示将要删除的记录数,不实际删除}';
  18. /**
  19. * 命令描述
  20. *
  21. * @var string
  22. */
  23. protected $description = '清理过期的用户日志记录';
  24. /**
  25. * 执行命令
  26. */
  27. public function handleRun()
  28. {
  29. $days = (int) $this->option('days');
  30. $dryRun = $this->option('dry-run');
  31. $this->info("开始清理 {$days} 天前的用户日志...");
  32. if ($dryRun) {
  33. $this->info('这是一次试运行,不会实际删除数据');
  34. // 计算将要删除的记录数
  35. $expiredDate = now()->subDays($days);
  36. $count = \App\Module\Game\Models\UserLog::where('created_at', '<', $expiredDate)->count();
  37. $this->info("将要删除 {$count} 条过期日志记录");
  38. $this->info("过期时间:{$expiredDate->toDateTimeString()}");
  39. return;
  40. }
  41. try {
  42. $deletedCount = UserLogService::cleanExpiredLogs($days);
  43. $this->info("成功清理 {$deletedCount} 条过期日志");
  44. } catch (\Exception $e) {
  45. $this->error("清理过期日志失败:{$e->getMessage()}");
  46. return 1;
  47. }
  48. return 0;
  49. }
  50. }