Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PHP] Fix empty message serialization for Any #10595

Merged
merged 1 commit into from
Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions php/src/Google/Protobuf/Internal/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -1980,8 +1980,12 @@ public function jsonByteSize()
$size += 9;
$size += $value_msg->jsonByteSize();
} else {
// Size for value. +1 for comma, -2 for "{}".
$size += $value_msg->jsonByteSize() -1;
$value_size = $value_msg->jsonByteSize();
// size === 2 it's empty message {} which is not serialized inside any
if ($value_size !== 2) {
// Size for value. +1 for comma, -2 for "{}".
$size += $value_size -1;
}
}
} elseif (get_class($this) === 'Google\Protobuf\FieldMask') {
$field_mask = GPBUtil::formatFieldMask($this);
Expand Down
19 changes: 19 additions & 0 deletions php/tests/EncodeDecodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

use Google\Protobuf\RepeatedField;
use Google\Protobuf\GPBType;
use Foo\EmptyAnySerialization;
use Foo\TestInt32Value;
use Foo\TestInt64Value;
use Foo\TestUInt32Value;
Expand Down Expand Up @@ -1513,4 +1514,22 @@ public function wrappersDataProvider()
[TestStringValue::class, "a", "\"a\"", "", "\"\""],
];
}

public function testEmptyAnySerialization()
{
$m = new EmptyAnySerialization();

$any = new Any();
$any->pack($m);

$data = $any->serializeToJsonString();
$this->assertEquals('{"@type":"type.googleapis.com/foo.EmptyAnySerialization"}', $data);

$any = new Any();
$any->mergeFromJsonString($data);

$m = $any->unpack();
$this->assertInstanceOf(EmptyAnySerialization::class, $m);
$this->assertEquals('', $m->getA());
}
}
4 changes: 4 additions & 0 deletions php/tests/proto/test.proto
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,10 @@ message ARRAY {
int32 a = 1;
}

message EmptyAnySerialization {
string a = 1;
}

message TestPackedMessage {
repeated int32 repeated_int32 = 90 [packed = true];
repeated int64 repeated_int64 = 91 [packed = true];
Expand Down