Protobuf.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Module\AppGame\Tools;
  3. use App\Module\AppGame\Events\ProtobufResponseEvent;
  4. use Google\Protobuf\Internal\Message;
  5. use Illuminate\Support\Facades\Event;
  6. use Uraus\Kku\Response;
  7. /**
  8. * protobuf 助手函数
  9. *
  10. */
  11. class Protobuf
  12. {
  13. /**
  14. * 进行 Response返回类型处理
  15. * @param Response $response
  16. * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Foundation\Application|\Illuminate\Http\JsonResponse|\Illuminate\Http\Response|object
  17. */
  18. public static function response(Response $response)
  19. {
  20. $httpRequest = request();
  21. // 触发 ProtobufResponse 返回前事件
  22. Event::dispatch(new ProtobufResponseEvent($response));
  23. // 根据请求的 Accept 头决定响应格式
  24. $acceptHeader = $httpRequest->header('Accept');
  25. $contentType = $httpRequest->header('Content-Type');
  26. if (stripos($acceptHeader, 'json') !== false || stripos($contentType, 'json') !== false) {
  27. // 返回 JSON 格式
  28. return response()->json(
  29. self::protobufToArray($response)
  30. );
  31. }
  32. // 返回 Protobuf 格式
  33. return response($response->serializeToString())
  34. ->header('Content-Type', 'application/x-protobuf');
  35. }
  36. /**
  37. * 将 Protobuf 消息对象转换为数组
  38. * @param Message $message Protobuf 消息对象
  39. * @return array
  40. */
  41. protected static function protobufToArray(Message $message): array
  42. {
  43. $json = $message->serializeToJsonString();
  44. return json_decode($json, true);
  45. }
  46. }