diff --git a/README.md b/README.md index 3d0723c..402357f 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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. diff --git a/src/Plugin/Compiler.php b/src/Plugin/Compiler.php index cca68ed..618ba42 100644 --- a/src/Plugin/Compiler.php +++ b/src/Plugin/Compiler.php @@ -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(); @@ -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; @@ -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()) { diff --git a/src/Plugin/OutputTable.php b/src/Plugin/OutputTable.php new file mode 100644 index 0000000..f74cce9 --- /dev/null +++ b/src/Plugin/OutputTable.php @@ -0,0 +1,98 @@ + source, package and namespace of the file a path is written for */ + private array $owners = []; + + public function __construct( + private readonly CompilerOptions $options, + ) {} + + /** + * @param iterable $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 $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, + ); + } +} diff --git a/tests/CompilerMultiplePackagesTest.php b/tests/CompilerMultiplePackagesTest.php new file mode 100644 index 0000000..019c898 --- /dev/null +++ b/tests/CompilerMultiplePackagesTest.php @@ -0,0 +1,169 @@ + $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}> + */ + 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 $files + * @param list $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, list}> + */ + 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 $files + * @return list + */ + 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 $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', + ); + } +}