Skip to content

Commit fae1d58

Browse files
authored
refactor(grpc): improve Parser::parseResponse return value format (#7653)
1 parent 7e891c6 commit fae1d58

File tree

1 file changed

+44
-5
lines changed

1 file changed

+44
-5
lines changed

src/Parser.php

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,45 @@ public static function parseResponse($response, $deserialize): array
7676
return [$reply, $status, $response];
7777
}
7878

79+
/**
80+
* @param null|Http2Response $response
81+
*/
82+
public static function parseMetadata($response): array
83+
{
84+
if (! $response || empty($response->headers)) {
85+
return [];
86+
}
87+
88+
$metadata = [];
89+
90+
foreach ($response->headers as $key => $value) {
91+
$lowerKey = strtolower($key);
92+
// 忽略grpc官方预留,将grpc-status-details-bin保留,可解析为Google\Rpc\Status
93+
if (str_starts_with($lowerKey, 'grpc-') && $lowerKey !== 'grpc-status-details-bin') {
94+
continue;
95+
}
96+
// 忽略http2预留伪头
97+
if (str_starts_with($lowerKey, ':')) {
98+
continue;
99+
}
100+
// 忽略 HTTP/2 传输层头部
101+
if (in_array($lowerKey, ['content-type', 'content-length', 'te'])) {
102+
continue;
103+
}
104+
// 处理-bin结尾 metadata
105+
if (str_ends_with($lowerKey, '-bin')) {
106+
if (($decoded = base64_decode($value, true)) !== false) {
107+
$metadata[$lowerKey][] = $decoded;
108+
}
109+
} else {
110+
// Handle ASCII URL-encoded metadata
111+
$metadata[$lowerKey][] = rawurldecode($value);
112+
}
113+
}
114+
115+
return $metadata;
116+
}
117+
79118
/**
80119
* @param Response $response
81120
*/
@@ -94,6 +133,11 @@ public static function statusToDetailsBin(Status $status): string
94133
return base64_encode(self::serializeUnpackedMessage($status));
95134
}
96135

136+
public static function isInvalidStatus(int $code): bool
137+
{
138+
return $code !== 0 && $code !== 200 && $code !== 400;
139+
}
140+
97141
private static function deserializeUnpackedMessage($deserialize, string $unpacked)
98142
{
99143
if (is_array($deserialize)) {
@@ -127,9 +171,4 @@ private static function serializeUnpackedMessage($data): string
127171

128172
return (string) $data;
129173
}
130-
131-
private static function isInvalidStatus(int $code): bool
132-
{
133-
return $code !== 0 && $code !== 200 && $code !== 400;
134-
}
135174
}

0 commit comments

Comments
 (0)