Skip to content
Draft
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
23 changes: 23 additions & 0 deletions php/src/Google/Protobuf/Internal/Message.php
Original file line number Diff line number Diff line change
Expand Up @@ -1540,6 +1540,19 @@ public function serializeToJsonStream(&$output)
return false;
}
}
} elseif (is_a($this, 'Google\Protobuf\Value')) {
$field = $this->desc->getFieldByName($this->getKind());
if (!$field) {
// A Value with no case of the oneof set is documented as 'invalid',
// but is trivially constructable and representable in binary format.
// Handle this as though `null_value` was set.
$output->writeRaw("null", 4);
return true;
} else {
if (!$this->serializeFieldToJsonStream($output, $field)) {
return false;
}
}
} else {
if (!GPBUtil::hasSpecialJsonMapping($this)) {
$output->writeRaw("{", 1);
Expand Down Expand Up @@ -2066,6 +2079,16 @@ public function jsonByteSize($options = 0)
// Size for "{}".
$size += 2;
}
} elseif (is_a($this, 'Google\Protobuf\Value')) {
$field = $this->desc->getFieldByName($this->getKind());
if (!$field) {
// A Value with no case of the oneof set is documented as
// 'invalid', but is trivially constructable and representable
// in binary format. Handle this as though `null_value` was set.
$size += 4;
} else {
$size += $this->fieldJsonByteSize($field, $options);
}
} else {
if (!GPBUtil::hasSpecialJsonMapping($this)) {
// Size for "{}".
Expand Down
23 changes: 23 additions & 0 deletions php/tests/EncodeDecodeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1159,6 +1159,9 @@ public function testDecodeTopLevelValue()

public function testEncodeTopLevelValue()
{
$m = new Value();
$this->assertSame("null", $m->serializeToJsonString());

$m = new Value();
$m->setStringValue("a");
$this->assertSame("\"a\"", $m->serializeToJsonString());
Expand All @@ -1176,6 +1179,26 @@ public function testEncodeTopLevelValue()
$this->assertSame("null", $m->serializeToJsonString());
}

public function testEncodeUnsetValue()
{
$m = new Struct();
$m->setFields(['k' => new Value()]);
$this->assertSame('{"k":null}', $m->serializeToJsonString());

$m = new ListValue();
$m->setValues([new Value(), new Value()]);
$this->assertSame('[null,null]', $m->serializeToJsonString());

// Unset Value decoded from 0-length sub-message wire bytes.
$m = new Struct();
$m->mergeFromString(hex2bin("0a050a016b1200"));
$this->assertSame('{"k":null}', $m->serializeToJsonString());

$m = new ListValue();
$m->mergeFromString(hex2bin("0a000a00"));
$this->assertSame('[null,null]', $m->serializeToJsonString());
}

public function testDecodeTopLevelListValue()
{
$m = new ListValue();
Expand Down
Loading