Skip to content

Commit

Permalink
Merge pull request #10595 from zajca/zajca-fix-10591
Browse files Browse the repository at this point in the history
[PHP] Fix empty message serialization for Any
  • Loading branch information
deannagarcia authored Oct 3, 2022
2 parents 7755973 + 743c675 commit a6eda18
Show file tree
Hide file tree
Showing 3 changed files with 29 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_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

0 comments on commit a6eda18

Please sign in to comment.