Skip to content

Commit 9fbce62

Browse files
fix(php): use count instead of ->count() to avoid bug in c-extension
PiperOrigin-RevId: 761147122
1 parent c149521 commit 9fbce62

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

php/tests/GeneratedClassTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,27 @@ public function testDeprecatedFieldGetterDoesNotThrowWarning()
130130
$this->assertEquals(0, $deprecationCount);
131131
}
132132

133+
public function testDeprecatedFieldSetterDoesNotThrowWarningForRepeatedAndMapFieldsWithEmptyArrays()
134+
{
135+
// temporarily change error handler to capture the deprecated errors
136+
$deprecationCount = 0;
137+
set_error_handler(function ($errno, $errstr) use (&$deprecationCount) {
138+
if (false !== strpos($errstr, ' is deprecated.')) {
139+
$deprecationCount++;
140+
}
141+
}, E_USER_DEPRECATED);
142+
143+
144+
// This behavior exists because otherwise the deprecation is thrown on serializeToJsonString
145+
$message = new TestMessage();
146+
$message->setDeprecatedRepeatedInt32([]); // repeated field
147+
$message->setDeprecatedMapInt32Int32([]); // map field
148+
149+
restore_error_handler();
150+
151+
$this->assertEquals(0, $deprecationCount);
152+
}
153+
133154
public function testDeprecatedFieldGetterThrowsWarningWithValue()
134155
{
135156
$message = new TestMessage([

src/google/protobuf/compiler/php/php_generator.cc

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ std::string DefaultForField(const FieldDescriptor* field) {
221221

222222
std::string DeprecatedConditionalForField(const FieldDescriptor* field) {
223223
if (field->is_repeated()) {
224-
return absl::StrCat("$this->", field->name(), "->count() !== 0");
224+
return absl::StrCat("count($this->", field->name(), ") !== 0");
225225
}
226226
if (field->real_containing_oneof() != nullptr) {
227227
return absl::StrCat("$this->hasOneof(", field->number(), ")");
@@ -749,7 +749,7 @@ void GenerateFieldAccessor(const FieldDescriptor* field, const Options& options,
749749

750750
if (field->options().deprecated() &&
751751
(field->is_map() || field->is_repeated())) {
752-
printer->Print("if ($arr->count() !== 0) {\n ^deprecation_trigger^}\n",
752+
printer->Print("if (count($arr) !== 0) {\n ^deprecation_trigger^}\n",
753753
"deprecation_trigger", deprecation_trigger);
754754
}
755755

0 commit comments

Comments
 (0)