TestItemTempCommand.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace App\Module\Game\Commands;
  3. use App\Module\Game\Services\ItemTempService;
  4. use App\Module\GameItems\Events\ItemQuantityChanged;
  5. use Illuminate\Console\Command;
  6. use Illuminate\Support\Facades\Event;
  7. /**
  8. * 测试物品暂存命令
  9. *
  10. * 用于测试物品变更事件监听和缓存功能
  11. */
  12. class TestItemTempCommand extends Command
  13. {
  14. /**
  15. * 命令名称
  16. *
  17. * @var string
  18. */
  19. protected $signature = 'game:test-item-temp {user_id} {item_id} {old_quantity} {new_quantity}';
  20. /**
  21. * 命令描述
  22. *
  23. * @var string
  24. */
  25. protected $description = '测试物品变更事件监听和缓存功能';
  26. /**
  27. * 物品缓存服务
  28. *
  29. * @var ItemTempService
  30. */
  31. protected $itemCacheService;
  32. /**
  33. * 创建命令实例
  34. */
  35. public function __construct(ItemTempService $itemCacheService)
  36. {
  37. parent::__construct();
  38. $this->itemCacheService = $itemCacheService;
  39. }
  40. /**
  41. * 执行命令
  42. */
  43. public function handle()
  44. {
  45. $userId = (int)$this->argument('user_id');
  46. $itemId = (int)$this->argument('item_id');
  47. $oldQuantity = (int)$this->argument('old_quantity');
  48. $newQuantity = (int)$this->argument('new_quantity');
  49. $this->info('测试物品变更事件监听和缓存功能');
  50. $this->info("用户ID: {$userId}");
  51. $this->info("物品ID: {$itemId}");
  52. $this->info("旧数量: {$oldQuantity}");
  53. $this->info("新数量: {$newQuantity}");
  54. // 清除之前的缓存
  55. $this->itemCacheService->clearUserItemChanges($userId);
  56. $this->info('已清除之前的缓存');
  57. // 触发物品数量变更事件
  58. $event = new ItemQuantityChanged(
  59. $userId,
  60. $itemId,
  61. null, // instanceId
  62. $oldQuantity,
  63. $newQuantity,
  64. 1, // userItemId
  65. ['source_type' => 'test', 'source_id' => 1]
  66. );
  67. Event::dispatch($event);
  68. $this->info('已触发物品数量变更事件');
  69. // 等待事件处理完成
  70. sleep(2);
  71. // 获取缓存数据
  72. $itemChanges = $this->itemCacheService->getUserItemChanges($userId);
  73. if (empty($itemChanges)) {
  74. $this->error('缓存数据为空,事件监听可能未正常工作');
  75. return 1;
  76. }
  77. $this->info('缓存数据:');
  78. $this->table(
  79. ['物品ID', '旧数量', '新数量', '变化量'],
  80. collect($itemChanges)->map(function ($item) {
  81. return [
  82. 'item_id' => $item['item_id'],
  83. 'old_quantity' => $item['old_quantity'],
  84. 'new_quantity' => $item['new_quantity'],
  85. 'change_amount' => $item['change_amount'],
  86. ];
  87. })->toArray()
  88. );
  89. $this->info('测试完成');
  90. return 0;
  91. }
  92. }