| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- namespace App\Module\AppGame\Tools;
- use App\Module\AppGame\Events\ProtobufResponseEvent;
- use Google\Protobuf\Internal\Message;
- use Illuminate\Support\Facades\Event;
- use Uraus\Kku\Response;
- /**
- * protobuf 助手函数
- *
- */
- class Protobuf
- {
- /**
- * 进行 Response返回类型处理
- * @param Response $response
- * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Foundation\Application|\Illuminate\Http\JsonResponse|\Illuminate\Http\Response|object
- */
- public static function response(Response $response)
- {
- $httpRequest = request();
- // 触发 ProtobufResponse 返回前事件
- Event::dispatch(new ProtobufResponseEvent($response));
- // 根据请求的 Accept 头决定响应格式
- $acceptHeader = $httpRequest->header('Accept');
- $contentType = $httpRequest->header('Content-Type');
- $ContentTypeBase64 = $httpRequest->header('Content-Type-Base64', 0);
- $ContentTypeBin = $httpRequest->header('Content-Type-Bin', 0);
- $forceJson = $httpRequest->header('Force-Json', 0);
- // 记录响应信息,便于调试
- \Illuminate\Support\Facades\Log::debug('Proto响应信息', [
- 'Accept' => $acceptHeader,
- 'Content-Type' => $contentType,
- 'Content-Type-Base64' => $ContentTypeBase64,
- 'Content-Type-Bin' => $ContentTypeBin,
- 'Force-Json' => $forceJson,
- 'response_size' => strlen($response->serializeToString()),
- 'response_json_size' => strlen($response->serializeToJsonString())
- ]);
- \Illuminate\Support\Facades\Log::debug('Proto响应信息-json', json_decode($response->serializeToJsonString(),true));
- // 强制返回JSON格式(用于调试或客户端不支持二进制解析时)
- if ($forceJson) {
- return response()->json(
- self::protobufToArray($response)
- )->header('Content-Type', 'application/json');
- }
- // 返回Base64编码的Protobuf数据
- if ($ContentTypeBase64) {
- $base64Data = base64_encode($response->serializeToString());
- return response($base64Data)
- ->header('Content-Type', 'text/plain');
- }
- // 返回JSON格式(当客户端请求JSON或发送JSON请求时)
- if ($ContentTypeBin == 0) {
- if (stripos($acceptHeader, 'json') !== false || stripos($contentType, 'json') !== false) {
- return response()->json(
- self::protobufToArray($response)
- );
- }
- }
- // 返回二进制Protobuf格式(默认)
- $binaryData = $response->serializeToString();
- return response($binaryData)
- ->header('Content-Type', 'application/x-protobuf');
- }
- /**
- * 将 Protobuf 消息对象转换为数组
- * @param Message $message Protobuf 消息对象
- * @return array
- */
- protected static function protobufToArray(Message $message): array
- {
- $json = $message->serializeToJsonString();
- return json_decode($json, true);
- }
- }
|