Skip to content

Commit

Permalink
fix empty message serialization for Any
Browse files Browse the repository at this point in the history
  • Loading branch information
zajca committed Sep 16, 2022
1 parent c4644b7 commit 80e9085
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
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_msg->jsonByteSize() -1;
}
}
} elseif (get_class($this) === 'Google\Protobuf\FieldMask') {
$field_mask = GPBUtil::formatFieldMask($this);
Expand Down
28 changes: 28 additions & 0 deletions php/tests/EncodeDecodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
require_once('test_base.php');
require_once('test_util.php');

use Foo\EmptyAnySerialization;
use Google\Protobuf\RepeatedField;
use Google\Protobuf\GPBType;
use Foo\TestInt32Value;
Expand Down Expand Up @@ -162,6 +163,15 @@ public function testEncodeTopLevelInt64Value()
$this->assertSame("\"1\"", $m->serializeToJsonString());
}

public function testEncodeTopLevelInt64ValueInAny()
{
$m = new Int64Value();
$m->setValue(1);
$any = new Any();
$any->pack($m);
$this->assertSame('{"@type":"type.googleapis.com/google.protobuf.Int64Value","value":"1"}', $any->serializeToJsonString());
}

public function testDecodeTopLevelUInt64Value()
{
$m = new UInt64Value();
Expand Down Expand Up @@ -1513,4 +1523,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

0 comments on commit 80e9085

Please sign in to comment.