| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- <?php
- namespace App\Module\Game\Logics\UserLogCollectors;
- use App\Module\Farm\Models\FarmHarvestLog;
- /**
- * 农场收获日志收集器
- *
- * 收集farm_harvest_logs表的新增记录,转换为用户友好的日志消息
- */
- class FarmHarvestLogCollector extends BaseLogCollector
- {
- /**
- * 源表名
- *
- * @var string
- */
- protected string $sourceTable = 'farm_harvest_logs';
- /**
- * 源类型
- *
- * @var string
- */
- protected string $sourceType = 'farm';
- /**
- * 获取新的记录
- *
- * @param int $lastProcessedId 上次处理的最大ID
- * @return \Illuminate\Database\Eloquent\Collection
- */
- protected function getNewRecords(int $lastProcessedId)
- {
- return FarmHarvestLog::where('id', '>', $lastProcessedId)
- ->orderBy('id')
- ->limit($this->maxRecords)
- ->get();
- }
- /**
- * 获取源表的最大ID
- *
- * 重写父类方法,使用模型查询以获得更好的性能
- *
- * @return int
- */
- public function getSourceTableMaxId(): int
- {
- return FarmHarvestLog::max('id') ?: 0;
- }
- /**
- * 转换记录为用户日志数据
- *
- * @param FarmHarvestLog $record 农场收获记录
- * @return array|null 用户日志数据,null表示跳过
- */
- protected function convertToUserLog($record): ?array
- {
- try {
- // 跳过收获数量为0的记录
- if ($record->output_amount <= 0) {
- return null;
- }
- // 获取作物名称
- $cropName = $this->getCropName($record->seed_id);
- // 构建收获消息
- $message = "收获{$record->land_id}号土地的{$cropName},获得{$record->output_amount}个";
- return $this->createUserLogData(
- $record->user_id,
- $message,
- $record->id,
- $record->created_at
- );
- } catch (\Exception $e) {
- \Illuminate\Support\Facades\Log::error("转换农场收获日志失败", [
- 'record_id' => $record->id,
- 'error' => $e->getMessage()
- ]);
- return null;
- }
- }
- /**
- * 获取作物名称
- *
- * @param int $seedId 种子ID
- * @return string
- */
- private function getCropName(int $seedId): string
- {
- try {
- // 尝试从配置中获取种子信息
- $seedConfig = \App\Module\Farm\Models\FarmSeed::find($seedId);
- if ($seedConfig) {
- return $seedConfig->name;
- }
-
- return "作物{$seedId}";
-
- } catch (\Exception $e) {
- return "作物{$seedId}";
- }
- }
- }
|