PetPowerRewardProcessor.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace App\Module\Game\Logics\RewardProcessors;
  3. use App\Module\Game\Dtos\RewardItemDto;
  4. use Exception;
  5. use Illuminate\Support\Facades\Log;
  6. use ReflectionClass;
  7. /**
  8. * 宠物体力奖励处理器
  9. *
  10. * 处理宠物体力(PET_POWER)类型的奖励发放
  11. */
  12. class PetPowerRewardProcessor
  13. {
  14. /**
  15. * 处理宠物体力奖励
  16. *
  17. * @param int $userId 用户ID
  18. * @param RewardItemDto $item 奖励项
  19. * @param string $sourceType 来源类型
  20. * @param int $sourceId 来源ID
  21. * @return void
  22. * @throws Exception
  23. */
  24. public static function process(int $userId, RewardItemDto $item, string $sourceType, int $sourceId): void
  25. {
  26. try {
  27. // 获取宠物ID和体力数量
  28. $petId = $item->targetId;
  29. $powerAmount = $item->quantity;
  30. // 验证宠物是否存在且属于该用户
  31. $pet = \App\Module\Pet\Models\PetUser::where('id', $petId)
  32. ->where('user_id', $userId)
  33. ->first();
  34. if (!$pet) {
  35. throw new Exception("宠物不存在或不属于该用户,宠物ID: {$petId},用户ID: {$userId}");
  36. }
  37. // 使用宠物逻辑类来增加体力
  38. $petLogic = new \App\Module\Pet\Logic\PetLogic();
  39. $reflection = new ReflectionClass($petLogic);
  40. $method = $reflection->getMethod('addStamina');
  41. $method->setAccessible(true);
  42. $actualGained = $method->invoke($petLogic, $petId, $powerAmount);
  43. Log::info("宠物体力奖励发放成功", [
  44. 'userId' => $userId,
  45. 'petId' => $petId,
  46. 'petName' => $pet->name,
  47. 'powerAmount' => $powerAmount,
  48. 'actualGained' => $actualGained,
  49. 'currentPower' => $pet->fresh()->stamina,
  50. 'sourceType' => $sourceType,
  51. 'sourceId' => $sourceId
  52. ]);
  53. } catch (Exception $e) {
  54. Log::error("宠物体力奖励发放失败", [
  55. 'userId' => $userId,
  56. 'petId' => $item->targetId,
  57. 'powerAmount' => $item->quantity,
  58. 'sourceType' => $sourceType,
  59. 'sourceId' => $sourceId,
  60. 'error' => $e->getMessage()
  61. ]);
  62. throw new Exception("宠物体力奖励发放失败: " . $e->getMessage());
  63. }
  64. }
  65. }