Skip to content

Commit 19adf03

Browse files
authored
Use protobuf PrintOptions if available (#1593)
Resolves #978
1 parent c43efe4 commit 19adf03

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

ProtobufSerializer.php

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,8 @@ public function serialize(Message $message): string
7373
// @phpstan-ignore-next-line
7474
return match ($this->contentType) {
7575
ContentTypes::PROTOBUF => $message->serializeToString(),
76-
ContentTypes::JSON => self::postProcessJsonEnumValues($message, $message->serializeToJsonString()),
77-
ContentTypes::NDJSON => self::postProcessJsonEnumValues($message, $message->serializeToJsonString()) . "\n",
76+
ContentTypes::JSON => self::serializeToJsonString($message),
77+
ContentTypes::NDJSON => self::serializeToJsonString($message) . "\n",
7878
};
7979
}
8080

@@ -92,16 +92,21 @@ public function hydrate(Message $message, string $payload): void
9292
}
9393

9494
/**
95-
* Workaround until protobuf exposes `FormatEnumsAsIntegers` option.
96-
*
9795
* [JSON Protobuf Encoding](https://opentelemetry.io/docs/specs/otlp/#json-protobuf-encoding):
9896
* > Values of enum fields MUST be encoded as integer values.
9997
*
10098
* @see https://github.com/open-telemetry/opentelemetry-php/issues/978
10199
* @see https://github.com/protocolbuffers/protobuf/pull/12707
102100
*/
103-
private static function postProcessJsonEnumValues(Message $message, string $payload): string
101+
private static function serializeToJsonString(Message $message): string
104102
{
103+
// @phan-suppress-next-line PhanUndeclaredClassReference
104+
if (\class_exists(\Google\Protobuf\PrintOptions::class)) {
105+
/** @psalm-suppress TooManyArguments @phan-suppress-next-line PhanParamTooManyInternal,PhanUndeclaredClassConstant @phpstan-ignore arguments.count */
106+
return $message->serializeToJsonString(\Google\Protobuf\PrintOptions::ALWAYS_PRINT_ENUMS_AS_INTS);
107+
}
108+
109+
$payload = $message->serializeToJsonString();
105110
$pool = DescriptorPool::getGeneratedPool();
106111
$desc = $pool->getDescriptorByClassName($message::class);
107112
if (!$desc instanceof Descriptor) {

0 commit comments

Comments
 (0)