Protobuf.php 1.4 KB

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