Skip to content
Merged
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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand Down
80 changes: 69 additions & 11 deletions src/Plugin/Generator/ProtoGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,9 @@ private function generateMessage(

$oneOfByIndex = [];

/** @var array<string, string> $properties property name => what generates it */
$properties = [];

foreach ($message->fields as $field) {
if ($field->oneOfIndex !== null && $field->proto3Optional === null) {
$oneOfByIndex[$field->oneOfIndex][] = $field;
Expand All @@ -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);

Expand Down Expand Up @@ -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)
Expand All @@ -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<string, string> $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] = [[], []];
Expand Down Expand Up @@ -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))));
}

/**
Expand Down
17 changes: 17 additions & 0 deletions src/Plugin/Naming.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
156 changes: 156 additions & 0 deletions tests/CompilerPropertyNameCollisionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
<?php

declare(strict_types=1);

namespace Thesis\Protoc;

use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Thesis\Google\Protobuf\Compiler\CodeGeneratorRequest;
use Thesis\Google\Protobuf\DescriptorProto;
use Thesis\Google\Protobuf\FieldDescriptorProto;
use Thesis\Google\Protobuf\FileDescriptorProto;
use Thesis\Google\Protobuf\OneofDescriptorProto;
use Thesis\Protobuf\Encoder;
use Thesis\Protoc\Exception\CodeCannotBeGenerated;
use Thesis\Protoc\Plugin\Compiler;
use Thesis\Protoc\Plugin\Generator\ProtoGenerator;

/**
* Two fields or oneofs of a message that end up with the same property are reported, not renamed: otherwise one
* constructor parameter silently replaces the other and the field is lost. protoc accepts each schema here (the
* descriptors are what it sends for the proto in the comment; in proto2 clashing JSON names are only a warning).
*/
#[CoversClass(Compiler::class)]
#[CoversClass(ProtoGenerator::class)]
final class CompilerPropertyNameCollisionTest extends TestCase
{
#[DataProvider('providePropertyCollisionIsReportedCases')]
public function testPropertyCollisionIsReported(DescriptorProto $message, string $syntax, string $error): void
{
$this->expectException(CodeCannotBeGenerated::class);
$this->expectExceptionMessage($error);

self::compile($message, $syntax);
}

/**
* @return iterable<string, array{DescriptorProto, string, string}>
*/
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<string, string> 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, '_'))),
);
}
}
44 changes: 44 additions & 0 deletions tests/GeneratedCode/samples/property_names.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

/**
* Populated messages of the property_names snapshot case, keyed by label (see GeneratedCodeTest).
*/

use Property\Names\Fields;
use Property\Names\ThisOneof;
use Property\Names\Variants;

return [
'fields named after a valid json_name, the field name and this_' => 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'),
),
];
Loading