CraftHandler.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace App\Module\AppGame\Handler\Item;
  3. use App\Module\AppGame\Handler\BaseHandler;
  4. use App\Module\GameItems\Services\CraftService;
  5. use Google\Protobuf\Internal\Message;
  6. use Illuminate\Support\Facades\Log;
  7. use Uraus\Kku\Request\RequestItemCraft;
  8. use Uraus\Kku\Response\ResponseItemCraft;
  9. use UCore\Exception\LogicException;
  10. /**
  11. * 处理物品合成请求
  12. */
  13. class CraftHandler extends BaseHandler
  14. {
  15. /**
  16. * 是否需要登录
  17. * @var bool
  18. */
  19. protected bool $need_login = true;
  20. /**
  21. * 处理物品合成请求
  22. *
  23. * @param RequestItemCraft $data 物品合成请求数据
  24. * @return ResponseItemCraft 物品合成响应
  25. */
  26. public function handle(Message $data): Message
  27. {
  28. // 创建响应对象
  29. $response = new ResponseItemCraft();
  30. try {
  31. // 获取请求参数
  32. $recipeId = $data->getId();
  33. $quantity = $data->getNumber();
  34. $userId = $this->user_id;
  35. // 验证参数
  36. if ($recipeId <= 0) {
  37. throw new LogicException("配方ID无效");
  38. }
  39. if ($quantity <= 0) {
  40. $quantity = 1; // 默认合成1个
  41. }
  42. // 调用合成服务
  43. $result = CraftService::craftItem($userId, $recipeId, [
  44. 'quantity' => $quantity,
  45. 'source_type' => 'app_craft',
  46. 'device_info' => request()->userAgent(),
  47. 'ip_address' => request()->ip(),
  48. ]);
  49. if (!$result) {
  50. throw new LogicException("合成失败,请检查材料是否充足或配方是否解锁");
  51. }
  52. // 设置响应状态
  53. $this->response->setCode(0);
  54. $this->response->setMsg('合成成功');
  55. Log::info('用户物品合成成功', [
  56. 'user_id' => $userId,
  57. 'recipe_id' => $recipeId,
  58. 'quantity' => $quantity,
  59. 'result' => $result
  60. ]);
  61. } catch (LogicException $e) {
  62. // 设置错误响应
  63. $this->response->setCode(400);
  64. $this->response->setMsg($e->getMessage());
  65. Log::warning('用户物品合成失败', [
  66. 'user_id' => $this->user_id,
  67. 'error' => $e->getMessage(),
  68. 'trace' => $e->getTraceAsString()
  69. ]);
  70. } catch (\Exception $e) {
  71. // 设置错误响应
  72. $this->response->setCode(500);
  73. $this->response->setMsg('系统错误,请稍后再试');
  74. Log::error('物品合成操作异常', [
  75. 'user_id' => $this->user_id,
  76. 'error' => $e->getMessage(),
  77. 'trace' => $e->getTraceAsString()
  78. ]);
  79. }
  80. return $response;
  81. }
  82. }