TestPetFeedEventCommand.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Module\Pet\Commands;
  3. use App\Module\Pet\Logic\PetLogic;
  4. use App\Module\Pet\Models\PetUser;
  5. use Illuminate\Console\Command;
  6. use Illuminate\Support\Facades\DB;
  7. use Illuminate\Support\Facades\Log;
  8. /**
  9. * 测试宠物喂养事件命令
  10. */
  11. class TestPetFeedEventCommand extends Command
  12. {
  13. /**
  14. * 命令签名
  15. *
  16. * @var string
  17. */
  18. protected $signature = 'pet:test-feed-event {pet_id} {item_id} {amount=1}';
  19. /**
  20. * 命令描述
  21. *
  22. * @var string
  23. */
  24. protected $description = '测试宠物喂养功能中的经验增加事件触发';
  25. /**
  26. * 执行命令
  27. *
  28. * @return int
  29. */
  30. public function handle(): int
  31. {
  32. $petId = (int) $this->argument('pet_id');
  33. $itemId = (int) $this->argument('item_id');
  34. $amount = (int) $this->argument('amount');
  35. try {
  36. // 检查宠物是否存在
  37. $pet = PetUser::find($petId);
  38. if (!$pet) {
  39. $this->error("宠物ID {$petId} 不存在");
  40. return 1;
  41. }
  42. $this->info("开始测试宠物喂养事件...");
  43. $this->info("宠物ID: {$petId}");
  44. $this->info("用户ID: {$pet->user_id}");
  45. $this->info("物品ID: {$itemId}");
  46. $this->info("数量: {$amount}");
  47. $this->info("当前经验: {$pet->experience}");
  48. $this->info("当前体力: {$pet->stamina}");
  49. // 开启事务并使用宠物逻辑类进行喂养
  50. DB::beginTransaction();
  51. try {
  52. $petLogic = new PetLogic();
  53. $feedResult = $petLogic->feedPet($petId, $itemId, $amount);
  54. DB::commit();
  55. } catch (\Exception $e) {
  56. DB::rollBack();
  57. throw $e;
  58. }
  59. // 刷新宠物数据
  60. $pet->refresh();
  61. $this->info("喂养成功!");
  62. $this->info("新经验值: {$pet->experience}");
  63. $this->info("新体力值: {$pet->stamina}");
  64. $this->info("经验增加: " . ($feedResult['exp_gained'] ?? 0));
  65. $this->info("体力增加: " . ($feedResult['stamina_gained'] ?? 0));
  66. $this->info("请检查日志以确认宠物经验增加事件已正确触发和处理");
  67. return 0;
  68. } catch (\Exception $e) {
  69. $this->error("测试失败: " . $e->getMessage());
  70. Log::error('宠物喂养测试失败', [
  71. 'pet_id' => $petId,
  72. 'item_id' => $itemId,
  73. 'amount' => $amount,
  74. 'error' => $e->getMessage()
  75. ]);
  76. return 1;
  77. }
  78. }
  79. }