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 @@ -138,6 +138,10 @@ protoc \
--php-plugin_out=src
```

The namespace applies to every file of the run, whatever its package. If two packages declare a class with the same name
(say, both have a message `User`), the plugin reports an error instead of writing both into one file: generate such packages
in separate `protoc` runs, each with its own `php_namespace`.

### `src_path`

If you are generating code within an application, you most likely want to place it in the `genproto/` or `generated/` folder
Expand All @@ -156,6 +160,10 @@ protoc \
--php-plugin_out=src
```

All the classes of the run are placed directly into this folder, whatever their namespace, so it is meant for files of one namespace.
If files of different namespaces declare a class with the same name, the plugin reports an error instead of writing both into one file:
generate such namespaces in separate `protoc` runs, each with its own `src_path`.

### `grpc`

Our plugin can generate not only protobuf messages, but also the client and server for `gRPC` services.
Expand Down
10 changes: 6 additions & 4 deletions src/Plugin/Compiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ private function doGenerate(

$registries = new DescriptorTable();

$outputs = new OutputTable($options);

foreach ($request as $source => $proto) {
$phpNamespace = $namespaces->file($proto) ?? throw self::namespaceCannotBeDetermined();

Expand All @@ -97,11 +99,11 @@ private function doGenerate(

foreach ($proto->services as $service) {
if ($options->requireGrpcClient) {
yield $generator->generateGrpcClient($service);
yield from $outputs->claim([$generator->generateGrpcClient($service)], $source, $proto, $phpNamespace);
}

if ($options->requireGrpcServer) {
yield from $generator->generateGrpcServer($service);
yield from $outputs->claim($generator->generateGrpcServer($service), $source, $proto, $phpNamespace);
}

$serviceName = ($proto->package !== null ? "{$proto->package}." : '') . $service->path;
Expand All @@ -126,10 +128,10 @@ static function (ServiceMethodDescriptor $method): File\MethodDescriptor {
));
}

yield from array_map($generator->generateEnum(...), $proto->enums);
yield from $outputs->claim(array_map($generator->generateEnum(...), $proto->enums), $source, $proto, $phpNamespace);

foreach ($proto->messages as $descriptor) {
yield from $this->doGenerateMessages($generator, $descriptor);
yield from $outputs->claim($this->doGenerateMessages($generator, $descriptor), $source, $proto, $phpNamespace);
}

if ($options->emitMetadata && !$index->empty()) {
Expand Down
98 changes: 98 additions & 0 deletions src/Plugin/OutputTable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

declare(strict_types=1);

namespace Thesis\Protoc\Plugin;

use Thesis\Google\Protobuf\Compiler\CodeGeneratorResponse;
use Thesis\Protoc\Exception\CodeCannotBeGenerated;

/**
* Remembers the .proto file each generated class is written for. Different packages are normally generated into
* different directories, but the src_path option puts every namespace into one directory and the php_namespace
* option (as well as one php_namespace file option shared by several packages) puts every package into one namespace.
* Two classes of different packages may then end up in one file, which is reported here instead of protoc's
* "Tried to write the same file twice".
*
* Two classes of a single package written to one file are a naming collision of another kind and are left to protoc.
*
* @internal
*/
final class OutputTable
{
/** @var array<string, array{string, string, string}> source, package and namespace of the file a path is written for */
private array $owners = [];

public function __construct(
private readonly CompilerOptions $options,
) {}

/**
* @param iterable<CodeGeneratorResponse\File> $files the classes generated for $source
* @param string $source the .proto file the classes are generated for
* @param string $namespace the PHP namespace of that file
* @return iterable<CodeGeneratorResponse\File> $files as they are
* @throws CodeCannotBeGenerated
*/
public function claim(
iterable $files,
string $source,
Parser\FileDescriptor $proto,
string $namespace,
): iterable {
foreach ($files as $file) {
$this->claimFile((string) $file->name, $source, $proto->package ?? '', $namespace);

yield $file;
}
}

/**
* @throws CodeCannotBeGenerated
*/
private function claimFile(string $path, string $source, string $package, string $namespace): void
{
if (!isset($this->owners[$path])) {
$this->owners[$path] = [$source, $package, $namespace];

return;
}

[$ownerSource, $ownerPackage, $ownerNamespace] = $this->owners[$path];

if ($ownerPackage === $package && $ownerNamespace === $namespace) {
return;
}

throw new CodeCannotBeGenerated(\sprintf(
'Files %s and %s both generate %s.%s',
self::describe($ownerSource, $ownerPackage, $ownerNamespace),
self::describe($source, $package, $namespace),
$path,
$this->hint($ownerNamespace, $namespace),
));
}

private function hint(string $ownerNamespace, string $namespace): string
{
if ($ownerNamespace !== $namespace && $this->options->srcPath !== null) {
return " The src_path={$this->options->srcPath} option puts the classes of every namespace into one directory, generate these packages in separate protoc runs with their own src_path.";
}

if ($ownerNamespace === $namespace && $namespace === $this->options->phpNamespace) {
return " The php_namespace={$namespace} option puts the classes of every package into one namespace, generate these packages in separate protoc runs with their own php_namespace.";
}

return '';
}

private static function describe(string $source, string $package, string $namespace): string
{
return \sprintf(
'%s (%s, namespace %s)',
$source,
$package === '' ? 'no package' : "package {$package}",
$namespace,
);
}
}
169 changes: 169 additions & 0 deletions tests/CompilerMultiplePackagesTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
<?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\Compiler\CodeGeneratorResponse\File;
use Thesis\Google\Protobuf\DescriptorProto;
use Thesis\Google\Protobuf\FileDescriptorProto;
use Thesis\Google\Protobuf\FileOptions;
use Thesis\Google\Protobuf\MethodDescriptorProto;
use Thesis\Google\Protobuf\ServiceDescriptorProto;
use Thesis\Protobuf\Encoder;
use Thesis\Protoc\Exception\CodeCannotBeGenerated;
use Thesis\Protoc\Plugin\Compiler;
use Thesis\Protoc\Plugin\OutputTable;

/**
* The src_path option puts every namespace into one directory, the php_namespace option puts every package into
* one namespace. Files of several packages generated in one run may then write two classes to one file, which is
* reported instead of protoc's "Tried to write the same file twice". Files of several packages whose classes do
* not collide are generated as before. Snapshots are generated without options, so these are unit tests.
*/
#[CoversClass(Compiler::class)]
#[CoversClass(OutputTable::class)]
final class CompilerMultiplePackagesTest extends TestCase
{
/**
* @param list<FileDescriptorProto> $files
*/
#[DataProvider('provideCollisionIsReportedCases')]
public function testCollisionIsReported(string $parameter, array $files, string $error): void
{
$this->expectException(CodeCannotBeGenerated::class);
$this->expectExceptionMessage($error);

self::compile($parameter, $files);
}

/**
* @return iterable<string, array{string, list<FileDescriptorProto>, string}>
*/
public static function provideCollisionIsReportedCases(): iterable
{
yield 'src_path and one message name in two packages' => [
'src_path=gen',
[self::file('a.proto', 'a.v1', ['M']), self::file('b.proto', 'b.v1', ['M'])],
'Files a.proto (package a.v1, namespace A\V1) and b.proto (package b.v1, namespace B\V1) both generate gen/M.php. The src_path=gen option puts the classes of every namespace into one directory, generate these packages in separate protoc runs with their own src_path.',
];

yield 'src_path, a grpc client and a message' => [
'src_path=.',
[self::file('a.proto', 'a.v1', ['Req'], service: 'Lookup'), self::file('b.proto', null, ['LookupClient'], phpNamespace: 'B')],
'Files a.proto (package a.v1, namespace A\V1) and b.proto (no package, namespace B) both generate ./LookupClient.php. The src_path=. option',
];

yield 'php_namespace and one message name in two packages' => [
'php_namespace=App\V1',
[self::file('a.proto', 'a.v1', ['M']), self::file('b.proto', 'b.v1', ['M'])],
'Files a.proto (package a.v1, namespace App\V1) and b.proto (package b.v1, namespace App\V1) both generate App/V1/M.php. The php_namespace=App\V1 option puts the classes of every package into one namespace, generate these packages in separate protoc runs with their own php_namespace.',
];

yield 'php_namespace, a grpc server and a message' => [
'php_namespace=App,grpc=server',
[self::file('a.proto', 'a.v1', ['Req'], service: 'Lookup'), self::file('b.proto', 'b.v1', ['LookupServerRegistry'])],
'Files a.proto (package a.v1, namespace App) and b.proto (package b.v1, namespace App) both generate App/LookupServerRegistry.php.',
];

yield 'src_path and php_namespace' => [
'src_path=gen,php_namespace=App',
[self::file('a.proto', 'a.v1', ['M']), self::file('b.proto', 'b.v1', ['M'])],
'Files a.proto (package a.v1, namespace App) and b.proto (package b.v1, namespace App) both generate gen/M.php. The php_namespace=App option',
];

yield 'one php_namespace file option in two packages' => [
'',
[self::file('a.proto', 'a.v1', ['M'], phpNamespace: 'Shared'), self::file('b.proto', 'b.v1', ['M'], phpNamespace: 'Shared')],
'Files a.proto (package a.v1, namespace Shared) and b.proto (package b.v1, namespace Shared) both generate Shared/M.php.',
];
}

/**
* @param list<FileDescriptorProto> $files
* @param list<string> $expected generated files
*/
#[DataProvider('provideNoCollisionCases')]
public function testNoCollision(string $parameter, array $files, array $expected): void
{
$generated = array_map(
static fn(File $file): ?string => $file->name,
self::compile($parameter, $files),
);

sort($generated);

self::assertSame($expected, $generated);
}

/**
* @return iterable<string, array{string, list<FileDescriptorProto>, list<string>}>
*/
public static function provideNoCollisionCases(): iterable
{
// The files of every namespace share the directory and a single registry, as before.
yield 'src_path' => [
'src_path=gen',
[self::file('a.proto', 'a.v1', ['M']), self::file('c.proto', 'c.v1', ['OnlyC'])],
['gen/DescriptorRegistry.php', 'gen/M.php', 'gen/OnlyC.php', 'gen/autoload.metadata.php'],
];

yield 'php_namespace' => [
'php_namespace=App\V1',
[self::file('a.proto', 'a.v1', ['M']), self::file('c.proto', 'c.v1', ['OnlyC'])],
['App/V1/DescriptorRegistry.php', 'App/V1/M.php', 'App/V1/OnlyC.php', 'App/V1/autoload.metadata.php'],
];

yield 'one message name in two packages without options' => [
'',
[self::file('a.proto', 'a.v1', ['M']), self::file('b.proto', 'b.v1', ['M'])],
['A/V1/DescriptorRegistry.php', 'A/V1/M.php', 'A/V1/autoload.metadata.php', 'B/V1/DescriptorRegistry.php', 'B/V1/M.php', 'B/V1/autoload.metadata.php'],
];
}

/**
* @param list<FileDescriptorProto> $files
* @return list<File>
*/
private static function compile(string $parameter, array $files): array
{
$request = new CodeGeneratorRequest(
fileToGenerate: array_map(static fn(FileDescriptorProto $file): string => (string) $file->name, $files),
parameter: $parameter,
protoFile: $files,
);

return new Compiler(Encoder\Builder::buildDefault(), __DIR__ . '/../map.json')->compile($request);
}

/**
* @param non-empty-list<string> $messages
*/
private static function file(
string $name,
?string $package,
array $messages,
?string $service = null,
?string $phpNamespace = null,
): FileDescriptorProto {
$type = '.' . ($package !== null ? "{$package}." : '') . $messages[0];

return new FileDescriptorProto(
name: $name,
package: $package,
messageType: array_map(static fn(string $message): DescriptorProto => new DescriptorProto(name: $message), $messages),
service: $service === null ? [] : [
new ServiceDescriptorProto(
name: $service,
method: [new MethodDescriptorProto(name: 'Get', inputType: $type, outputType: $type)],
),
],
options: $phpNamespace === null ? null : new FileOptions(phpNamespace: $phpNamespace),
syntax: 'proto3',
);
}
}