| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- <?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');
- if (stripos($acceptHeader, 'json') !== false || stripos($contentType, 'json') !== false) {
- // 返回 JSON 格式
- return response()->json(
- self::protobufToArray($response)
- );
- }
- // 返回 Protobuf 格式
- return response($response->serializeToString())
- ->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);
- }
- }
|