FarmHarvestLogCollector.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace App\Module\Game\Logics\UserLogCollectors;
  3. use App\Module\Farm\Models\FarmHarvestLog;
  4. /**
  5. * 农场收获日志收集器
  6. *
  7. * 收集farm_harvest_logs表的新增记录,转换为用户友好的日志消息
  8. */
  9. class FarmHarvestLogCollector extends BaseLogCollector
  10. {
  11. /**
  12. * 源表名
  13. *
  14. * @var string
  15. */
  16. protected string $sourceTable = 'farm_harvest_logs';
  17. /**
  18. * 源类型
  19. *
  20. * @var string
  21. */
  22. protected string $sourceType = 'farm';
  23. /**
  24. * 获取新的记录
  25. *
  26. * @param int $lastProcessedId 上次处理的最大ID
  27. * @return \Illuminate\Database\Eloquent\Collection
  28. */
  29. protected function getNewRecords(int $lastProcessedId)
  30. {
  31. return FarmHarvestLog::where('id', '>', $lastProcessedId)
  32. ->orderBy('id')
  33. ->limit($this->maxRecords)
  34. ->get();
  35. }
  36. /**
  37. * 获取源表的最大ID
  38. *
  39. * 重写父类方法,使用模型查询以获得更好的性能
  40. *
  41. * @return int
  42. */
  43. public function getSourceTableMaxId(): int
  44. {
  45. return FarmHarvestLog::max('id') ?: 0;
  46. }
  47. /**
  48. * 转换记录为用户日志数据
  49. *
  50. * @param FarmHarvestLog $record 农场收获记录
  51. * @return array|null 用户日志数据,null表示跳过
  52. */
  53. protected function convertToUserLog($record): ?array
  54. {
  55. try {
  56. // 跳过收获数量为0的记录
  57. if ($record->output_amount <= 0) {
  58. return null;
  59. }
  60. // 获取作物名称
  61. $cropName = $this->getCropName($record->seed_id);
  62. // 构建收获消息
  63. $message = "收获{$record->land_id}号土地的{$cropName},获得{$record->output_amount}个";
  64. return $this->createUserLogData(
  65. $record->user_id,
  66. $message,
  67. $record->id,
  68. $record->created_at
  69. );
  70. } catch (\Exception $e) {
  71. \Illuminate\Support\Facades\Log::error("转换农场收获日志失败", [
  72. 'record_id' => $record->id,
  73. 'error' => $e->getMessage()
  74. ]);
  75. return null;
  76. }
  77. }
  78. /**
  79. * 获取作物名称
  80. *
  81. * @param int $seedId 种子ID
  82. * @return string
  83. */
  84. private function getCropName(int $seedId): string
  85. {
  86. try {
  87. // 尝试从配置中获取种子信息
  88. $seedConfig = \App\Module\Farm\Models\FarmSeed::find($seedId);
  89. if ($seedConfig) {
  90. return $seedConfig->name;
  91. }
  92. return "作物{$seedId}";
  93. } catch (\Exception $e) {
  94. return "作物{$seedId}";
  95. }
  96. }
  97. }