diff --git a/README.md b/README.md index 9ef8e80..d777d34 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ For this reason, we have written this plugin, which — in addition to addressin - [multiple options](#multiple-options) - [Namespace mapping](#namespace-mapping) - [Generated code guide](#generated-code-guide) + - [property names](#property-names) - [numbers](#numbers) - [repeated](#repeated) - [maps](#maps) @@ -297,6 +298,13 @@ That is what keeps `Any` type urls and server reflection interoperable: other la As mentioned above, the plugin generates simple DTOs without setters, getters, or inheritance. All metadata for protobuf serialization is stored in attribute `Thesis\Protobuf\Reflection\*`, and the generated DTOs only have a constructor with promoted properties. +#### property names + +A property is named after the field's `json_name`: by default it is the field name in lowerCamelCase (`chat_id` → `$chatId`), a custom `[json_name = "..."]` renames the property. +When the `json_name` is not a valid PHP variable name (`"my-field"`, `"@type"`, `"1st"`), the property is named after the field name in camelCase instead, and the variant class of a `oneof` likewise. +`this` (a field or a `oneof`) becomes `$this_`; other reserved words stay as they are (`$class`, `$list`). The property of a `oneof` is named after the `oneof`. +Two fields or `oneof`s of a message that end up with the same property name (for example, field `fooBar` and `oneof foo_bar`) fail the generation with an error naming both. + #### numbers To avoid issues with integer overflow when using `int64/uint64` types, `\BcMath\Number` will be used. diff --git a/src/Plugin/Generator/ProtoGenerator.php b/src/Plugin/Generator/ProtoGenerator.php index e0d3a5f..0daf069 100644 --- a/src/Plugin/Generator/ProtoGenerator.php +++ b/src/Plugin/Generator/ProtoGenerator.php @@ -313,6 +313,9 @@ private function generateMessage( $oneOfByIndex = []; + /** @var array $properties property name => what generates it */ + $properties = []; + foreach ($message->fields as $field) { if ($field->oneOfIndex !== null && $field->proto3Optional === null) { $oneOfByIndex[$field->oneOfIndex][] = $field; @@ -326,11 +329,9 @@ private function generateMessage( throw new CodeCannotBeGenerated('DELIMITED message encoding are not supported'); } - $parameterName = $field->jsonName; + $parameterName = self::fieldPropertyName($field); - if ($parameterName === null || $parameterName === '') { - $parameterName = Naming::propertyName($field->name); - } + self::claimPropertyName($properties, $message, $parameterName, "field {$field->name}"); $parameter = $constructor->addPromotedParameter($parameterName); @@ -446,8 +447,12 @@ private function generateMessage( // Variants are named after the oneof itself, even when its interface has been renamed. $oneOfName = Naming::pascalCase($oneOf->name); + $propertyName = self::oneofPropertyName($oneOf); + + self::claimPropertyName($properties, $message, $propertyName, "oneof {$oneOf->name}"); + $constructor - ->addPromotedParameter(Naming::propertyName($oneOf->name)) + ->addPromotedParameter($propertyName) ->setType($this->namespacer->fqcn("{$message->path}.{$oneofInterfaces[$idx]}")) ->setNullable() ->setDefaultValue(null) @@ -471,6 +476,23 @@ private function generateMessage( return $namespace; } + /** + * Two fields or oneofs of one message must not end up with the same property, which would silently drop one of them. + * protoc rejects only clashing JSON names, and in proto2 merely warns about them, while a property name + * also comes from a oneof name or from the fallback of fieldBaseName(). PHP variable names are case-sensitive. + * + * @param array $properties + * @throws CodeCannotBeGenerated + */ + private static function claimPropertyName(array &$properties, Parser\MessageDescriptor $message, string $name, string $owner): void + { + if (isset($properties[$name])) { + throw new CodeCannotBeGenerated("Message {$message->fqcn}: the {$properties[$name]} and the {$owner} both become the property \${$name}."); + } + + $properties[$name] = $owner; + } + private function reorderRequiredFirst(Method $constructor): void { [$required, $optional] = [[], []]; @@ -738,15 +760,51 @@ static function (array $matches) use ($simple, &$valid): string { return $valid ? $bytes : null; } - private static function oneofVariantName(string $oneof, Parser\FieldDescriptor $variant): string + /** + * The name the property of $field and the class of a oneof variant holding $field are built from. It is the + * json_name of the field while that is a valid PHP variable name, so a custom json_name names the property. + * A json_name that is not ("my-field", "@type", "1st") gives way to the field name in camelCase, which for + * an ordinary field name is what protoc puts into json_name by default. protoc always fills json_name, + * the fallback also covers descriptors without it. + */ + private static function fieldBaseName(Parser\FieldDescriptor $field): string { - if ($variant->jsonName !== null) { - $name = \sprintf('%s%s', Naming::pascalCase($oneof), ucfirst($variant->jsonName)); - } else { - $name = Naming::pascalCase("{$oneof} {$variant->name}"); + if ($field->jsonName !== null && Naming::isVariableName($field->jsonName)) { + return $field->jsonName; } - return Naming::secure($name); + return Naming::propertyName($field->name); + } + + /** + * The name of the property, i.e. of the promoted constructor parameter, generated for $field, see fieldBaseName(). + * The only place it is decided: the parameter, its `@param` tag and the property of a oneof variant class take it from here. + */ + private static function fieldPropertyName(Parser\FieldDescriptor $field): string + { + return self::variableName(self::fieldBaseName($field), $field->name); + } + + /** + * The name of the property generated for $oneof. + */ + private static function oneofPropertyName(Parser\OneOfDescriptor $oneof): string + { + return self::variableName(Naming::propertyName($oneof->name), $oneof->name); + } + + /** + * $name with `this` escaped. Only a proto name like `_1st` turns into a camelCase that is not a variable name ("1st"): + * then the proto name itself is used, a proto identifier always being a valid PHP one. + */ + private static function variableName(string $name, string $protoName): string + { + return Naming::secureVariable(Naming::isVariableName($name) ? $name : $protoName); + } + + private static function oneofVariantName(string $oneof, Parser\FieldDescriptor $variant): string + { + return Naming::secure(\sprintf('%s%s', Naming::pascalCase($oneof), ucfirst(self::fieldBaseName($variant)))); } /** diff --git a/src/Plugin/Naming.php b/src/Plugin/Naming.php index aea15ad..acf7340 100644 --- a/src/Plugin/Naming.php +++ b/src/Plugin/Naming.php @@ -215,6 +215,23 @@ public static function secure(string $name): string return isset(self::CLASS_NAMES_RESERVED_WORDS[strtolower($name)]) ? "{$name}_" : $name; } + /** + * Whether $name can be the name of a PHP variable, and so of a promoted constructor parameter: + * a PHP identifier, where every byte from 0x80 up counts as a letter (so a non-ASCII UTF-8 name is valid). + */ + public static function isVariableName(string $name): bool + { + return preg_match('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/D', $name) === 1; + } + + /** + * Reserved words are valid property and parameter names, `$this` is the only one PHP rejects for a parameter. + */ + public static function secureVariable(string $name): string + { + return $name === 'this' ? 'this_' : $name; + } + public static function secureEnumCase(string $name): string { return isset(self::ENUM_CASE_RESERVED_WORDS[strtolower($name)]) ? "{$name}_" : $name; diff --git a/tests/CompilerPropertyNameCollisionTest.php b/tests/CompilerPropertyNameCollisionTest.php new file mode 100644 index 0000000..3ea4c42 --- /dev/null +++ b/tests/CompilerPropertyNameCollisionTest.php @@ -0,0 +1,156 @@ +expectException(CodeCannotBeGenerated::class); + $this->expectExceptionMessage($error); + + self::compile($message, $syntax); + } + + /** + * @return iterable + */ + public static function providePropertyCollisionIsReportedCases(): iterable + { + // syntax = "proto2"; message A { optional string a = 1 [json_name = "b"]; optional string b = 2; } + yield 'custom json_name and the json_name of another field' => [ + new DescriptorProto( + name: 'A', + field: [self::field('a', 1, jsonName: 'b'), self::field('b', 2)], + ), + 'proto2', + 'Message t.A: the field a and the field b both become the property $b.', + ]; + + // message A { string fooBar = 1; oneof foo_bar { string x = 2; } } + yield 'field and oneof' => [ + new DescriptorProto( + name: 'A', + field: [self::field('fooBar', 1), self::field('x', 2, oneofIndex: 0)], + oneofDecl: [new OneofDescriptorProto('foo_bar')], + ), + 'proto3', + 'Message t.A: the field fooBar and the oneof foo_bar both become the property $fooBar.', + ]; + + // message A { string this = 1; string a = 2 [json_name = "this_"]; } + yield 'escaped this and a field named this_' => [ + new DescriptorProto( + name: 'A', + field: [self::field('this', 1), self::field('a', 2, jsonName: 'this_')], + ), + 'proto3', + 'Message t.A: the field this and the field a both become the property $this_.', + ]; + + // message A { string a = 1 [json_name = "this_"]; oneof this { string b = 2; } } + yield 'field named this_ and escaped oneof this' => [ + new DescriptorProto( + name: 'A', + field: [self::field('a', 1, jsonName: 'this_'), self::field('b', 2, oneofIndex: 0)], + oneofDecl: [new OneofDescriptorProto('this')], + ), + 'proto3', + 'Message t.A: the field a and the oneof this both become the property $this_.', + ]; + + // message A { string my_field = 1 [json_name = "my-field"]; string other = 2 [json_name = "myField"]; } + yield 'name derived from an invalid json_name and the json_name of another field' => [ + new DescriptorProto( + name: 'A', + field: [self::field('my_field', 1, jsonName: 'my-field'), self::field('other', 2, jsonName: 'myField')], + ), + 'proto3', + 'Message t.A: the field my_field and the field other both become the property $myField.', + ]; + } + + /** + * message A { string a = 1 [json_name = "Foo"]; string foo = 2; }: PHP variable names are case-sensitive. + */ + public function testPropertiesDifferingInCaseDoNotCollide(): void + { + $files = self::compile( + new DescriptorProto( + name: 'A', + field: [self::field('a', 1, jsonName: 'Foo'), self::field('foo', 2)], + ), + 'proto3', + ); + + self::assertArrayHasKey('T/A.php', $files); + self::assertStringContainsString('public string $Foo = \'\',', $files['T/A.php']); + self::assertStringContainsString('public string $foo = \'\',', $files['T/A.php']); + } + + /** + * @return array file name => content + */ + private static function compile(DescriptorProto $message, string $syntax): array + { + $request = new CodeGeneratorRequest( + fileToGenerate: ['t.proto'], + protoFile: [ + new FileDescriptorProto( + name: 't.proto', + package: 't', + messageType: [$message], + syntax: $syntax === 'proto2' ? null : $syntax, + ), + ], + ); + + $compiler = new Compiler(Encoder\Builder::buildDefault(), __DIR__ . '/../map.json'); + + $files = []; + + foreach ($compiler->compile($request) as $file) { + $files[(string) $file->name] = (string) $file->content; + } + + return $files; + } + + /** + * A string field with the json_name protoc fills in: the custom one, or the field name in lowerCamelCase. + */ + private static function field(string $name, int $number, ?string $jsonName = null, ?int $oneofIndex = null): FieldDescriptorProto + { + return new FieldDescriptorProto( + name: $name, + number: $number, + label: FieldDescriptorProto\Label::LABEL_OPTIONAL, + type: FieldDescriptorProto\Type::TYPE_STRING, + oneofIndex: $oneofIndex, + jsonName: $jsonName ?? lcfirst(str_replace('_', '', ucwords($name, '_'))), + ); + } +} diff --git a/tests/GeneratedCode/samples/property_names.php b/tests/GeneratedCode/samples/property_names.php new file mode 100644 index 0000000..a2b5ad1 --- /dev/null +++ b/tests/GeneratedCode/samples/property_names.php @@ -0,0 +1,44 @@ + new Fields( + this_: 'this', + dashed: 'my-field', + withSpace: 'with space', + first: '1st', + typeUrl: '@type', + привет: 'привет', + renamed: 'renamed', + class: 'class', + list: 'list', + static: 'static', + commentedField: 'commented', + repeatedValues: [1, -2, 3], + _1st_place: '_1st_place', + ), + 'oneof this set to a variant with an invalid json_name' => new ThisOneof( + this_: new ThisOneof\ThisNumber(number: 42), + ), + 'oneof this set to a variant with a default json_name' => new ThisOneof( + this_: new ThisOneof\ThisText(text: 'text'), + ), + 'variant holding the field this' => new Variants( + payload: new Variants\PayloadThis(this_: 'this'), + ), + 'variant with an invalid json_name' => new Variants( + payload: new Variants\PayloadRawValue(rawValue: 'raw'), + ), + 'variant with a valid custom json_name' => new Variants( + payload: new Variants\PayloadKept(Kept: 'kept'), + ), +]; diff --git a/tests/NamingTest.php b/tests/NamingTest.php index 88b9fc7..2eabad3 100644 --- a/tests/NamingTest.php +++ b/tests/NamingTest.php @@ -93,4 +93,32 @@ public function testSecure(string $actual, string $expected): void { self::assertSame($expected, Naming::secure($actual)); } + + #[TestWith(['foo', true])] + #[TestWith(['fooBar', true])] + #[TestWith(['_1st', true])] + #[TestWith(['_', true])] + #[TestWith(['class', true])] + #[TestWith(['this', true])] + #[TestWith(['привет', true])] + #[TestWith(['', false])] + #[TestWith(['1st', false])] + #[TestWith(['my-field', false])] + #[TestWith(['with space', false])] + #[TestWith(['@type', false])] + #[TestWith(["foo\n", false])] + public function testIsVariableName(string $name, bool $expected): void + { + self::assertSame($expected, Naming::isVariableName($name)); + } + + #[TestWith(['this', 'this_'])] + #[TestWith(['This', 'This'])] + #[TestWith(['this_', 'this_'])] + #[TestWith(['class', 'class'])] + #[TestWith(['static', 'static'])] + public function testSecureVariable(string $name, string $expected): void + { + self::assertSame($expected, Naming::secureVariable($name)); + } } diff --git a/tests/fixtures/property_names/property_names.proto b/tests/fixtures/property_names/property_names.proto new file mode 100644 index 0000000..ecd4db0 --- /dev/null +++ b/tests/fixtures/property_names/property_names.proto @@ -0,0 +1,37 @@ +syntax = "proto3"; + +package property.names; + +// The property of a field is named after its json_name while that is a valid PHP variable name, +// otherwise after the field name in camelCase; `this` becomes `this_`. +message Fields { + string this = 1; + string dashed = 2 [json_name = "my-field"]; + string with_space = 3 [json_name = "with space"]; + string first = 4 [json_name = "1st"]; + string type_url = 5 [json_name = "@type"]; + string greeting = 6 [json_name = "привет"]; + string custom = 7 [json_name = "renamed"]; + string keyword = 8 [json_name = "class"]; + string list = 9; + string static = 10; + // The comment of a field with an invalid json_name. + string commented_field = 11 [json_name = "commented-field"]; + repeated int32 repeated_values = 12 [json_name = "repeated values"]; + string _1st_place = 13; +} + +message ThisOneof { + oneof this { + string text = 1; + int32 number = 2 [json_name = "the-number"]; + } +} + +message Variants { + oneof payload { + string this = 1; + string raw_value = 2 [json_name = "raw-value"]; + string kept = 3 [json_name = "Kept"]; + } +} diff --git a/tests/snapshots/property_names/Property/Names/DescriptorRegistry.php b/tests/snapshots/property_names/Property/Names/DescriptorRegistry.php new file mode 100644 index 0000000..8a64a0f --- /dev/null +++ b/tests/snapshots/property_names/Property/Names/DescriptorRegistry.php @@ -0,0 +1,38 @@ +add(Registry\Descriptor::base64(self::PROPERTY_NAMES_DESCRIPTOR_BUFFER), new File( + name: 'property_names.proto', + messages: [ + new File\MessageDescriptor('property.names.Fields', \Property\Names\Fields::class), + new File\MessageDescriptor('property.names.ThisOneof', \Property\Names\ThisOneof::class), + new File\MessageDescriptor('property.names.Variants', \Property\Names\Variants::class), + ], + )); + } +} diff --git a/tests/snapshots/property_names/Property/Names/Fields.php b/tests/snapshots/property_names/Property/Names/Fields.php new file mode 100644 index 0000000..c28c197 --- /dev/null +++ b/tests/snapshots/property_names/Property/Names/Fields.php @@ -0,0 +1,57 @@ + $repeatedValues + */ + public function __construct( + #[Reflection\Field(1, Reflection\StringT::T)] + public string $this_ = '', + #[Reflection\Field(2, Reflection\StringT::T)] + public string $dashed = '', + #[Reflection\Field(3, Reflection\StringT::T)] + public string $withSpace = '', + #[Reflection\Field(4, Reflection\StringT::T)] + public string $first = '', + #[Reflection\Field(5, Reflection\StringT::T)] + public string $typeUrl = '', + #[Reflection\Field(6, Reflection\StringT::T)] + public string $привет = '', + #[Reflection\Field(7, Reflection\StringT::T)] + public string $renamed = '', + #[Reflection\Field(8, Reflection\StringT::T)] + public string $class = '', + #[Reflection\Field(9, Reflection\StringT::T)] + public string $list = '', + #[Reflection\Field(10, Reflection\StringT::T)] + public string $static = '', + #[Reflection\Field(11, Reflection\StringT::T)] + public string $commentedField = '', + #[Reflection\Field(12, new Reflection\ListT(Reflection\Int32T::T))] + public array $repeatedValues = [], + #[Reflection\Field(13, Reflection\StringT::T)] + public string $_1st_place = '', + ) {} +} diff --git a/tests/snapshots/property_names/Property/Names/ThisOneof.php b/tests/snapshots/property_names/Property/Names/ThisOneof.php new file mode 100644 index 0000000..bad5cf8 --- /dev/null +++ b/tests/snapshots/property_names/Property/Names/ThisOneof.php @@ -0,0 +1,26 @@ +register( + new \Thesis\Protobuf\Registry\OnceRegistrar(new \Property\Names\DescriptorRegistry()), +);