From 310f341473038f29523ae3090bdaef5b1d74afe4 Mon Sep 17 00:00:00 2001 From: John Charman Date: Wed, 23 Sep 2026 15:07:55 +0100 Subject: [PATCH 1/9] Update Router to ^0.6 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index d1ad813c..9ebb28e9 100644 --- a/composer.json +++ b/composer.json @@ -20,7 +20,7 @@ "psr/log": "^3.0.2", "symfony/console": "^7.4.19 || ^8.1.7", "membrane/openapi-reader": "^3.1.1", - "membrane/openapi-router": "0.5.3" + "membrane/openapi-router": "^0.6" }, "require-dev": { "phpunit/phpunit": "^13.1.14", From 2df29e3a34dadbd5ff1797b6311d98f7c27f993e Mon Sep 17 00:00:00 2001 From: John Charman Date: Wed, 23 Sep 2026 15:08:15 +0100 Subject: [PATCH 2/9] Add RouteMatch specification --- src/OpenAPI/Specification/RouteMatch.php | 25 ++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 src/OpenAPI/Specification/RouteMatch.php diff --git a/src/OpenAPI/Specification/RouteMatch.php b/src/OpenAPI/Specification/RouteMatch.php new file mode 100644 index 00000000..2f798e24 --- /dev/null +++ b/src/OpenAPI/Specification/RouteMatch.php @@ -0,0 +1,25 @@ +operationId, + $routeMatch->source, + ); + } +} From 8dc6e984b69ec096e1d6352358b5c408b9020498 Mon Sep 17 00:00:00 2001 From: John Charman Date: Wed, 23 Sep 2026 15:08:35 +0100 Subject: [PATCH 3/9] Add RouteMatch Builder template --- src/Console/Template/RouteMatchBuilder.php | 86 ++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 src/Console/Template/RouteMatchBuilder.php diff --git a/src/Console/Template/RouteMatchBuilder.php b/src/Console/Template/RouteMatchBuilder.php new file mode 100644 index 00000000..1cb4d799 --- /dev/null +++ b/src/Console/Template/RouteMatchBuilder.php @@ -0,0 +1,86 @@ +source === self::OPEN_API_FILENAME + && isset(self::MAP[$specification->operationId]); + } + + public function build(Specification $specification): Processor + { + assert($this->supports($specification)); + + return new (self::MAP[$specification->operationId])(); + } +} +END; + + private readonly string $openAPIFilePath; + + /** @param array $map */ + public function __construct( + private readonly string $namespace, + private readonly string $className, + string $openAPIFilePath, + private readonly array $map + ) { + $this->openAPIFilePath = realpath($openAPIFilePath) ?: $openAPIFilePath; + } + + public function getNamespace(): string + { + return $this->namespace; + } + + public function getName(): string + { + return 'CachedRouteMatchBuilder'; + } + + public function getCode(): string + { + $implodedMap = ''; + foreach ($this->map as $operationId => $processor) { + $implodedMap .= sprintf('\'%s\' => \'%s\', ', $operationId, $processor); + } + + return sprintf( + self::TEMPLATE_CODE, + $this->namespace, + $this->className, + $this->openAPIFilePath, + $implodedMap, + ); + } +} From ba437b12a92957736a1194afaa75aabc38883cad Mon Sep 17 00:00:00 2001 From: John Charman Date: Wed, 23 Sep 2026 16:15:23 +0100 Subject: [PATCH 4/9] Pass `routeMatch` flag through to YieldsClassDefinitions --- .../Command/CacheOpenAPIProcessors.php | 23 ++++++++++-- .../Service/CacheOpenAPIProcessors.php | 6 ++-- .../Service/YieldsClassDefinitions.php | 35 +++++++------------ 3 files changed, 37 insertions(+), 27 deletions(-) diff --git a/src/Console/Command/CacheOpenAPIProcessors.php b/src/Console/Command/CacheOpenAPIProcessors.php index 2946031c..e565e162 100644 --- a/src/Console/Command/CacheOpenAPIProcessors.php +++ b/src/Console/Command/CacheOpenAPIProcessors.php @@ -54,6 +54,14 @@ protected function configure(): void 'Skip generation of Response processors', null, ); + + self::addOption( + 'route-match', + null, + InputOption::VALUE_NONE, + 'Use RouteMatch Builder for multi-file request handling', + null, + ); } protected function execute(InputInterface $input, OutputInterface $output): int @@ -68,16 +76,27 @@ protected function execute(InputInterface $input, OutputInterface $output): int assert(is_bool($skipResponses)); $skipRequests = $input->getOption('skip-requests'); assert(is_bool($skipRequests)); + $routeMatch = $input->getOption('skip-requests'); + assert(is_bool($routeMatch)); $consoleLogger = new ConsoleLogger($output); if ($skipResponses && $skipRequests) { - $consoleLogger->warning('Skipping both requests and responses, nothing will be generated'); + $consoleLogger->warning( + 'Skipping both requests and responses, nothing will be generated', + ); } $cachingService = new \Membrane\Console\Service\CacheOpenAPIProcessors($consoleLogger); - $success = $cachingService->cache($openAPIFilePath, $destination, $namespace, !$skipRequests, !$skipResponses); + $success = $cachingService->cache( + $openAPIFilePath, + $destination, + $namespace, + !$skipRequests, + !$skipResponses, + $routeMatch, + ); return $success ? Command::SUCCESS : Command::FAILURE; } } diff --git a/src/Console/Service/CacheOpenAPIProcessors.php b/src/Console/Service/CacheOpenAPIProcessors.php index 321b4aac..7e0e8a02 100644 --- a/src/Console/Service/CacheOpenAPIProcessors.php +++ b/src/Console/Service/CacheOpenAPIProcessors.php @@ -9,8 +9,6 @@ use Membrane\OpenAPIReader\Exception\CannotRead; use Membrane\OpenAPIReader\Exception\CannotSupport; use Membrane\OpenAPIReader\Exception\InvalidOpenAPI; -use Membrane\OpenAPIReader\MembraneReader; -use Membrane\OpenAPIReader\OpenAPIVersion; use Psr\Log\LoggerInterface; class CacheOpenAPIProcessors @@ -25,7 +23,8 @@ public function cache( string $cacheDestinationFilePath, string $cacheNamespace, bool $buildRequests = true, - bool $buildResponses = true + bool $buildResponses = true, + bool $routeMatch = false, ): bool { $yieldsClasses = new YieldsClassDefinitions($this->logger); @@ -35,6 +34,7 @@ public function cache( $cacheNamespace, $buildRequests, $buildResponses, + $routeMatch, )); $destination = rtrim($cacheDestinationFilePath, '/'); diff --git a/src/Console/Service/YieldsClassDefinitions.php b/src/Console/Service/YieldsClassDefinitions.php index 11d626f7..98baa9c8 100644 --- a/src/Console/Service/YieldsClassDefinitions.php +++ b/src/Console/Service/YieldsClassDefinitions.php @@ -6,8 +6,7 @@ use Membrane\Console\Template; use Membrane\Filter; -use Membrane\OpenAPI\Builder\Internal\Request; -use Membrane\OpenAPI\Builder\Internal\Response; +use Membrane\OpenAPI\Builder\Internal; use Membrane\OpenAPI\ExtractPathParameters\PathParameterExtractor; use Membrane\OpenAPIReader\MembraneReader; use Membrane\OpenAPIReader\OpenAPIVersion; @@ -15,8 +14,8 @@ final class YieldsClassDefinitions { - private Request $requestBuilder; - private Response $responseBuilder; + private Internal\Request $requestBuilder; + private Internal\Response $responseBuilder; public function __construct( private readonly \Psr\Log\LoggerInterface $logger, @@ -28,6 +27,7 @@ public function __invoke( string $cacheNamespace, bool $buildRequests, bool $buildResponses, + bool $routeMatch, ): \Generator { $openAPI = $this->readOpenAPIFile($openAPIFilePath); @@ -109,19 +109,19 @@ private function readOpenAPIFile(string $filepath): V30\OpenAPI | V31\OpenAPI /** @param array $existingClassNames */ private function createSuitableClassName(string $nameToConvert, array $existingClassNames): string { - $pascalCaseName = (new Filter\String\ToPascalCase())->filter($nameToConvert)->value; - $alphanumericName = (new Filter\String\AlphaNumeric())->filter($pascalCaseName)->value; - + $pascalCaseName = new Filter\String\ToPascalCase()->filter($nameToConvert)->value; + $alphanumericName = new Filter\String\AlphaNumeric()->filter($pascalCaseName)->value; assert(is_string($alphanumericName)); + if (is_numeric($alphanumericName[0])) { $alphanumericName = 'm' . $alphanumericName; } - if (in_array($alphanumericName, $existingClassNames)) { + if (in_array($alphanumericName, $existingClassNames, true)) { $i = 1; do { $postfixedName = sprintf('%s%d', $alphanumericName, $i++); - } while (in_array($postfixedName, $existingClassNames)); + } while (in_array($postfixedName, $existingClassNames, true)); return $postfixedName; } @@ -130,22 +130,13 @@ private function createSuitableClassName(string $nameToConvert, array $existingC } - private function getRequestBuilder(): Request + private function getRequestBuilder(): Internal\Request { - if (!isset($this->requestBuilder)) { - $this->requestBuilder = new Request(); - return $this->requestBuilder; - } - - return $this->requestBuilder; + return $this->requestBuilder ??= new Internal\Request(); } - private function getResponseBuilder(): Response + private function getResponseBuilder(): Internal\Response { - if (!isset($this->responseBuilder)) { - $this->responseBuilder = new Response(); - return $this->responseBuilder; - } - return $this->responseBuilder; + return $this->responseBuilder ??= new Internal\Response(); } } From 03f887c195f4b55da40bf73448a9d8e8000dc752 Mon Sep 17 00:00:00 2001 From: John Charman Date: Wed, 23 Sep 2026 16:18:44 +0100 Subject: [PATCH 5/9] Use braced variables in strings --- src/Console/Service/YieldsClassDefinitions.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Console/Service/YieldsClassDefinitions.php b/src/Console/Service/YieldsClassDefinitions.php index 98baa9c8..b8cd5874 100644 --- a/src/Console/Service/YieldsClassDefinitions.php +++ b/src/Console/Service/YieldsClassDefinitions.php @@ -43,17 +43,17 @@ public function __invoke( $classNames[$operationId] = $className = $this->createSuitableClassName($operationId, $classNames); $classMap[$operationId] = [ - 'request' => "$cacheNamespace\\Request\\$className", + 'request' => "{$cacheNamespace}\\Request\\{$className}", 'response' => [], ]; if ($buildRequests) { $this->logger->info( - "Generating $cacheNamespace\\Request\\$className" + "Generating {$cacheNamespace}\\Request\\{$className}" ); yield new Template\Processor( - namespace: "$cacheNamespace\\Request", + namespace: "{$cacheNamespace}\\Request", name: $className, processor: $this->getRequestBuilder()->build( new PathParameterExtractor($pathUrl), @@ -67,11 +67,11 @@ public function __invoke( foreach ($operation->responses as $code => $response) { $prefixedCode = 'Code' . ucwords((string) $code); $this->logger->info( - "Generating $cacheNamespace\\Response\\$prefixedCode\\$className" + "Generating {$cacheNamespace}\\Response\\{$prefixedCode}\\{$className}" ); yield new Template\Processor( - namespace: "$cacheNamespace\\Response\\$prefixedCode", + namespace: "{$cacheNamespace}\\Response\\{$prefixedCode}", name: $className, processor: $this->getResponseBuilder()->build($response), ); From 4c3e5c1b50e47ed7b85f7890b4ecf2fc37955400 Mon Sep 17 00:00:00 2001 From: John Charman Date: Wed, 23 Sep 2026 16:33:52 +0100 Subject: [PATCH 6/9] Split YieldsClassDefinitions into two branches The default branch yields the default behaviour. If $routeMatch is set to true, then it yieldsRouteMatch instead --- .../Service/CacheOpenAPIProcessors.php | 2 +- .../Service/YieldsClassDefinitions.php | 32 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/Console/Service/CacheOpenAPIProcessors.php b/src/Console/Service/CacheOpenAPIProcessors.php index 7e0e8a02..ddda4eb2 100644 --- a/src/Console/Service/CacheOpenAPIProcessors.php +++ b/src/Console/Service/CacheOpenAPIProcessors.php @@ -41,7 +41,7 @@ public function cache( $classWriter = new PHPFilesWriter($destination, $cacheNamespace); $classWriter->writeFiles($definitionProducer); } catch (CannotRead | CannotSupport | InvalidOpenAPI | \RuntimeException $e) { - // TODO do not catch RuntimeException once PHPFilesWriter throws specific exceptions + //@TODO do not catch RuntimeException once PHPFilesWriter throws specific exceptions $this->logger->error($e->getMessage()); return false; } diff --git a/src/Console/Service/YieldsClassDefinitions.php b/src/Console/Service/YieldsClassDefinitions.php index b8cd5874..bea1ddfe 100644 --- a/src/Console/Service/YieldsClassDefinitions.php +++ b/src/Console/Service/YieldsClassDefinitions.php @@ -28,6 +28,29 @@ public function __invoke( bool $buildRequests, bool $buildResponses, bool $routeMatch, + ): \Generator { + if ($routeMatch) { + return $this->yieldRouteMatch( + $openAPIFilePath, + $cacheNamespace, + $buildRequests, + $buildResponses, + ); + } + + return $this->yieldRequestsAndResponses( + $openAPIFilePath, + $cacheNamespace, + $buildRequests, + $buildResponses, + ); + } + + private function yieldRequestsAndResponses( + string $openAPIFilePath, + string $cacheNamespace, + bool $buildRequests, + bool $buildResponses, ): \Generator { $openAPI = $this->readOpenAPIFile($openAPIFilePath); @@ -97,6 +120,15 @@ public function __invoke( } } + private function yieldRouteMatch( + string $openAPIFilePath, + string $cacheNamespace, + bool $buildRequests, + bool $buildResponses, + ): \Generator { + yield []; + } + private function readOpenAPIFile(string $filepath): V30\OpenAPI | V31\OpenAPI { $this->logger->info("Reading OpenAPI from $filepath"); From 2842522a1dc9e19631198f4cf0f982c290023046 Mon Sep 17 00:00:00 2001 From: John Charman Date: Wed, 23 Sep 2026 16:42:24 +0100 Subject: [PATCH 7/9] Optimize default path with static anonymous functions --- src/Console/Service/YieldsClassDefinitions.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Console/Service/YieldsClassDefinitions.php b/src/Console/Service/YieldsClassDefinitions.php index bea1ddfe..978af353 100644 --- a/src/Console/Service/YieldsClassDefinitions.php +++ b/src/Console/Service/YieldsClassDefinitions.php @@ -104,17 +104,17 @@ private function yieldRequestsAndResponses( if ($buildRequests) { yield new Template\RequestBuilder( - "$cacheNamespace", + $cacheNamespace, $openAPIFilePath, - array_map(fn($p) => $p['request'], $classMap), + array_map(static fn($p) => $p['request'], $classMap), ); } if ($buildResponses) { yield new Template\ResponseBuilder( - "$cacheNamespace", + $cacheNamespace, $openAPIFilePath, - array_map(fn($p) => $p['response'], $classMap), + array_map(static fn($p) => $p['response'], $classMap), ); } } From f6c06bc3aa1974eb53b2b461a775f44cb52e75c5 Mon Sep 17 00:00:00 2001 From: John Charman Date: Thu, 24 Sep 2026 13:33:44 +0100 Subject: [PATCH 8/9] Add option to build RouteBuilder --- bin/membrane | 6 +- .../Command/CacheOpenAPIProcessors.php | 46 +++++-- .../Service/CacheOpenAPIProcessors.php | 63 +++++++-- ...ssDefinitions.php => YieldsProcessors.php} | 122 ++++++++---------- src/Console/Template/RequestBuilder.php | 13 +- src/Console/Template/ResponseBuilder.php | 13 +- src/Console/Template/RouteMatchBuilder.php | 19 ++- .../Service/CacheOpenAPIProcessorsTest.php | 27 +++- tests/Console/Template/RequestBuilderTest.php | 20 ++- .../Console/Template/ResponseBuilderTest.php | 22 +++- .../Template/RouteMatchBuilderTest.php | 120 +++++++++++++++++ 11 files changed, 339 insertions(+), 132 deletions(-) rename src/Console/Service/{YieldsClassDefinitions.php => YieldsProcessors.php} (56%) create mode 100644 tests/Console/Template/RouteMatchBuilderTest.php diff --git a/bin/membrane b/bin/membrane index 6bbd6fb6..d75ee5ce 100755 --- a/bin/membrane +++ b/bin/membrane @@ -21,15 +21,15 @@ use Symfony\Component\Console\Application; $application = new Application(); if (class_exists(CacheOpenAPIProcessors::class)) { - $application->add(new CacheOpenAPIProcessors()); + $application->addCommand(new CacheOpenAPIProcessors()); } if (class_exists(CacheOpenAPI::class)) { - $application->add(new CacheOpenAPI()); + $application->addCommand(new CacheOpenAPI()); } if (class_exists(CacheOpenAPIRoutes::class)) { - $application->add(new CacheOpenAPIRoutes()); + $application->addCommand(new CacheOpenAPIRoutes()); } $application->run(); diff --git a/src/Console/Command/CacheOpenAPIProcessors.php b/src/Console/Command/CacheOpenAPIProcessors.php index e565e162..a620474c 100644 --- a/src/Console/Command/CacheOpenAPIProcessors.php +++ b/src/Console/Command/CacheOpenAPIProcessors.php @@ -4,6 +4,7 @@ namespace Membrane\Console\Command; +use Membrane\Console\Service; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\{InputArgument, InputInterface, InputOption}; @@ -30,7 +31,6 @@ protected function configure(): void getcwd() . '/cache' ); - self::addOption( 'namespace', null, @@ -39,6 +39,22 @@ protected function configure(): void 'Membrane\Cache' ); + self::addOption( + 'request-processor-classname', + null, + InputOption::VALUE_OPTIONAL, + 'Classname for the generated request processor', + 'CachedRequestBuilder' + ); + + self::addOption( + 'response-processor-classname', + null, + InputOption::VALUE_OPTIONAL, + 'Classname for the generated response processor', + 'CachedResponseBuilder' + ); + self::addOption( 'skip-requests', null, @@ -62,6 +78,8 @@ protected function configure(): void 'Use RouteMatch Builder for multi-file request handling', null, ); + + } protected function execute(InputInterface $input, OutputInterface $output): int @@ -76,8 +94,12 @@ protected function execute(InputInterface $input, OutputInterface $output): int assert(is_bool($skipResponses)); $skipRequests = $input->getOption('skip-requests'); assert(is_bool($skipRequests)); - $routeMatch = $input->getOption('skip-requests'); + $routeMatch = $input->getOption('route-match'); assert(is_bool($routeMatch)); + $requestName = $input->getOption('request-processor-classname'); + assert(is_string($requestName)); + $responseName = $input->getOption('response-processor-classname'); + assert(is_string($responseName)); $consoleLogger = new ConsoleLogger($output); @@ -87,16 +109,18 @@ protected function execute(InputInterface $input, OutputInterface $output): int ); } - $cachingService = new \Membrane\Console\Service\CacheOpenAPIProcessors($consoleLogger); + $success = new Service\CacheOpenAPIProcessors($consoleLogger) + ->cache( + $openAPIFilePath, + $destination, + $namespace, + !$skipRequests, + !$skipResponses, + $routeMatch, + $requestName, + $responseName, + ); - $success = $cachingService->cache( - $openAPIFilePath, - $destination, - $namespace, - !$skipRequests, - !$skipResponses, - $routeMatch, - ); return $success ? Command::SUCCESS : Command::FAILURE; } } diff --git a/src/Console/Service/CacheOpenAPIProcessors.php b/src/Console/Service/CacheOpenAPIProcessors.php index ddda4eb2..059795f9 100644 --- a/src/Console/Service/CacheOpenAPIProcessors.php +++ b/src/Console/Service/CacheOpenAPIProcessors.php @@ -6,6 +6,7 @@ use Atto\CodegenTools\ClassDefinition\PHPClassDefinitionProducer; use Atto\CodegenTools\CodeGeneration\PHPFilesWriter; +use Membrane\Console\Template; use Membrane\OpenAPIReader\Exception\CannotRead; use Membrane\OpenAPIReader\Exception\CannotSupport; use Membrane\OpenAPIReader\Exception\InvalidOpenAPI; @@ -24,24 +25,66 @@ public function cache( string $cacheNamespace, bool $buildRequests = true, bool $buildResponses = true, - bool $routeMatch = false, + bool $buildRouteMatch = false, + string $requestClassname = 'CachedRequestBuilder', + string $responseClassname = 'CachedResponseBuilder', ): bool { - $yieldsClasses = new YieldsClassDefinitions($this->logger); + $yieldsClasses = new YieldsProcessors( + $this->logger, + $openAPIFilePath, + $cacheNamespace, + $buildRequests, + $buildResponses, + ); + + $gensClasses = function () use ( + $yieldsClasses, + $openAPIFilePath, + $cacheNamespace, + $buildRequests, + $buildResponses, + $buildRouteMatch, + $requestClassname, + $responseClassname, + ) { + yield from $yieldsClasses(); + + if ($buildRequests) { + if ($buildRouteMatch) { + yield new Template\RouteMatchBuilder( + $cacheNamespace, + $requestClassname, + $openAPIFilePath, + array_map(fn($p) => $p['request'], $yieldsClasses->classMap), + ); + } else { + yield new Template\RequestBuilder( + $cacheNamespace, + $requestClassname, + $openAPIFilePath, + array_map(fn($p) => $p['request'], $yieldsClasses->classMap), + ); + } + } + + if ($buildResponses) { + yield new Template\ResponseBuilder( + $cacheNamespace, + $responseClassname, + $openAPIFilePath, + array_map(fn($p) => $p['response'], $yieldsClasses->classMap), + ); + } + }; try { - $definitionProducer = new PHPClassDefinitionProducer($yieldsClasses( - $openAPIFilePath, - $cacheNamespace, - $buildRequests, - $buildResponses, - $routeMatch, - )); + $definitionProducer = new PHPClassDefinitionProducer($gensClasses()); $destination = rtrim($cacheDestinationFilePath, '/'); $classWriter = new PHPFilesWriter($destination, $cacheNamespace); $classWriter->writeFiles($definitionProducer); } catch (CannotRead | CannotSupport | InvalidOpenAPI | \RuntimeException $e) { - //@TODO do not catch RuntimeException once PHPFilesWriter throws specific exceptions + // TODO do not catch RuntimeException once PHPFilesWriter throws specific exceptions $this->logger->error($e->getMessage()); return false; } diff --git a/src/Console/Service/YieldsClassDefinitions.php b/src/Console/Service/YieldsProcessors.php similarity index 56% rename from src/Console/Service/YieldsClassDefinitions.php rename to src/Console/Service/YieldsProcessors.php index 978af353..22bb41ec 100644 --- a/src/Console/Service/YieldsClassDefinitions.php +++ b/src/Console/Service/YieldsProcessors.php @@ -11,53 +11,36 @@ use Membrane\OpenAPIReader\MembraneReader; use Membrane\OpenAPIReader\OpenAPIVersion; use Membrane\OpenAPIReader\ValueObject\Valid\{Enum\Method, V30, V31}; +use Psr\Log\LoggerInterface; -final class YieldsClassDefinitions +final class YieldsProcessors { private Internal\Request $requestBuilder; private Internal\Response $responseBuilder; + /** @var array, + * }> + */ + private(set) array $classMap; + public function __construct( - private readonly \Psr\Log\LoggerInterface $logger, + private readonly LoggerInterface $logger, + private readonly string $apiFilePath, + private readonly string $cacheNamespace, + private readonly bool $buildRequests, + private readonly bool $buildResponses, ) { } - public function __invoke( - string $openAPIFilePath, - string $cacheNamespace, - bool $buildRequests, - bool $buildResponses, - bool $routeMatch, - ): \Generator { - if ($routeMatch) { - return $this->yieldRouteMatch( - $openAPIFilePath, - $cacheNamespace, - $buildRequests, - $buildResponses, - ); - } - - return $this->yieldRequestsAndResponses( - $openAPIFilePath, - $cacheNamespace, - $buildRequests, - $buildResponses, - ); - } - - private function yieldRequestsAndResponses( - string $openAPIFilePath, - string $cacheNamespace, - bool $buildRequests, - bool $buildResponses, - ): \Generator { - $openAPI = $this->readOpenAPIFile($openAPIFilePath); + public function __invoke(): \Generator + { + $this->classMap = []; - // Initialize classMap for CachedBuilers - $classNames = []; - $classMap = []; + $openAPI = $this->readOpenAPIFile($this->apiFilePath); + $classNames = []; // to avoid duplicates classNames foreach ($openAPI->paths as $pathUrl => $path) { foreach ($path->getOperations() as $method => $operation) { $methodObject = Method::from(strtolower($method)); @@ -65,68 +48,65 @@ private function yieldRequestsAndResponses( $classNames[$operationId] = $className = $this->createSuitableClassName($operationId, $classNames); - $classMap[$operationId] = [ - 'request' => "{$cacheNamespace}\\Request\\{$className}", + $this->classMap[$operationId] = [ + 'request' => $this->getRequestFQCN($className), 'response' => [], ]; - if ($buildRequests) { - $this->logger->info( - "Generating {$cacheNamespace}\\Request\\{$className}" - ); + if ($this->buildRequests) { + $this->logger + ->info("Generating {$this->getRequestFQCN($className)}"); yield new Template\Processor( - namespace: "{$cacheNamespace}\\Request", + namespace: $this->getRequestNamespace(), name: $className, processor: $this->getRequestBuilder()->build( new PathParameterExtractor($pathUrl), $path, $methodObject, - ) + ), ); } - if ($buildResponses) { + if ($this->buildResponses) { foreach ($operation->responses as $code => $response) { $prefixedCode = 'Code' . ucwords((string) $code); - $this->logger->info( - "Generating {$cacheNamespace}\\Response\\{$prefixedCode}\\{$className}" - ); + + $this->classMap[$operationId]['responses'] []= $this + ->getResponseFQCN($prefixedCode, $className); + + $this->logger + ->info("Generating {$this->getResponseFQCN($prefixedCode, $className)}"); yield new Template\Processor( - namespace: "{$cacheNamespace}\\Response\\{$prefixedCode}", + namespace: $this->getResponseNamespace($prefixedCode), name: $className, processor: $this->getResponseBuilder()->build($response), ); } } } + } + } - if ($buildRequests) { - yield new Template\RequestBuilder( - $cacheNamespace, - $openAPIFilePath, - array_map(static fn($p) => $p['request'], $classMap), - ); - } + private function getRequestNamespace(): string + { + return "{$this->cacheNamespace}\\Request"; + } - if ($buildResponses) { - yield new Template\ResponseBuilder( - $cacheNamespace, - $openAPIFilePath, - array_map(static fn($p) => $p['response'], $classMap), - ); - } - } + private function getRequestFQCN(string $name): string + { + return "{$this->getRequestNamespace()}\\{$name}"; } - private function yieldRouteMatch( - string $openAPIFilePath, - string $cacheNamespace, - bool $buildRequests, - bool $buildResponses, - ): \Generator { - yield []; + private function getResponseNamespace(string $code): string + { + return "{$this->cacheNamespace}\\Response\\{$code}"; + } + + private function getResponseFQCN(string $code, string $name): string + { + return "{$this->getResponseNamespace($code)}\\{$name}"; } private function readOpenAPIFile(string $filepath): V30\OpenAPI | V31\OpenAPI diff --git a/src/Console/Template/RequestBuilder.php b/src/Console/Template/RequestBuilder.php index 60ff16ac..89693399 100644 --- a/src/Console/Template/RequestBuilder.php +++ b/src/Console/Template/RequestBuilder.php @@ -21,7 +21,7 @@ class RequestBuilder implements PHPClassDefinition use Membrane\OpenAPIRouter\Router; use Membrane\OpenAPI\Specification\Request as RequestSpecification; -class CachedRequestBuilder implements Builder +class %s implements Builder { private const OPEN_API_FILENAME = '%s'; private const MAP = [%s]; @@ -73,6 +73,7 @@ private function getOperationId(RequestSpecification $specification): string /** @param array $map */ public function __construct( private readonly string $namespace, + private readonly string $className, string $openAPIFilePath, private readonly array $map ) { @@ -86,7 +87,7 @@ public function getNamespace(): string public function getName(): string { - return 'CachedRequestBuilder'; + return $this->className; } public function getCode(): string @@ -96,6 +97,12 @@ public function getCode(): string $implodedMap .= sprintf('\'%s\' => \'%s\', ', $operationId, $processor); } - return sprintf(self::TEMPLATE_CODE, $this->namespace, $this->openAPIFilePath, $implodedMap); + return sprintf( + self::TEMPLATE_CODE, + $this->namespace, + $this->className, + $this->openAPIFilePath, + $implodedMap, + ); } } diff --git a/src/Console/Template/ResponseBuilder.php b/src/Console/Template/ResponseBuilder.php index 3d2c3aed..728f0e89 100644 --- a/src/Console/Template/ResponseBuilder.php +++ b/src/Console/Template/ResponseBuilder.php @@ -21,7 +21,7 @@ class ResponseBuilder implements PHPClassDefinition use Membrane\OpenAPIRouter\Router; use \Membrane\OpenAPI\Specification\Response as ResponseSpecification; -class CachedResponseBuilder implements Builder +class %s implements Builder { private const OPEN_API_FILENAME = '%s'; private const MAP = [%s]; @@ -72,6 +72,7 @@ private function getOperationId(ResponseSpecification $specification): string /** @param array> $map */ public function __construct( private readonly string $namespace, + private readonly string $className, string $openAPIFilePath, private readonly array $map ) { @@ -85,7 +86,7 @@ public function getNamespace(): string public function getName(): string { - return 'CachedResponseBuilder'; + return $this->className; } public function getCode(): string @@ -103,6 +104,12 @@ public function getCode(): string $implodedMap .= sprintf('\'%s\' => [%s], ', $operationId, $implodedResponses); } - return sprintf(self::TEMPLATE_CODE, $this->namespace, $this->openAPIFilePath, $implodedMap); + return sprintf( + self::TEMPLATE_CODE, + $this->namespace, + $this->className, + $this->openAPIFilePath, + $implodedMap, + ); } } diff --git a/src/Console/Template/RouteMatchBuilder.php b/src/Console/Template/RouteMatchBuilder.php index 1cb4d799..b324c25f 100644 --- a/src/Console/Template/RouteMatchBuilder.php +++ b/src/Console/Template/RouteMatchBuilder.php @@ -15,25 +15,22 @@ class RouteMatchBuilder implements PHPClassDefinition namespace %s; -use Membrane\Builder\Builder; -use Membrane\Builder\Specification; +use Membrane\Builder\{Builder, Specification}; use Membrane\OpenAPI\Specification\RouteMatch; -use Membrane\OpenAPIRouter\Router; use Membrane\Processor; class %s implements Builder { - private const OPEN_API_FILENAME = '%s'; - private const MAP = [%s]; + private const string OPEN_API_FILENAME = '%s'; + private const array MAP = [%s]; - /** @phpstan-assert-if-true RouteMatch $specification */ + /** + * @phpstan-assert-if-true RouteMatch $specification + */ public function supports(Specification $specification): bool { - if (!$specification instanceof RouteMatch) { - return false; - } - - return $specification->source === self::OPEN_API_FILENAME + return $specification instanceof RouteMatch + && realpath($specification->source) === self::OPEN_API_FILENAME && isset(self::MAP[$specification->operationId]); } diff --git a/tests/Console/Service/CacheOpenAPIProcessorsTest.php b/tests/Console/Service/CacheOpenAPIProcessorsTest.php index 9c5b46ec..3da31e67 100644 --- a/tests/Console/Service/CacheOpenAPIProcessorsTest.php +++ b/tests/Console/Service/CacheOpenAPIProcessorsTest.php @@ -80,7 +80,11 @@ public function failsOnReadonlyDestinations(): void chmod($this->root->url(), 0444); $readonlyDestination = $this->root->url() . '/cache'; - $actual = $this->sut->cache($correctApiPath, $readonlyDestination, 'Membrane\\Cache'); + $actual = $this->sut->cache( + $correctApiPath, + $readonlyDestination, + 'Membrane\\Cache', + ); self::assertFalse($actual); } @@ -103,7 +107,11 @@ public static function provideCasesThatFailToRead(): array #[DataProvider('provideCasesThatFailToRead')] public function failsOnUnreadableOpenAPI(string $openAPI, string $destination): void { - $actual = $this->sut->cache($openAPI, $destination, 'Membrane\\Cache'); + $actual = $this->sut->cache( + $openAPI, + $destination, + 'Membrane\\Cache', + ); self::assertFalse($actual); } @@ -127,7 +135,11 @@ public function cachesProcessorsWithSuitableNamesToAvoidDuplicates(): void Method::GET, ); - $this->sut->cache($hatstoreFilePath, $this->root->url() . '/cache/', 'ServiceTest\\Hatstore'); + $this->sut->cache( + $hatstoreFilePath, + $this->root->url() . '/cache/', + 'ServiceTest\\Hatstore', + ); eval('//' . file_get_contents($this->root->getChild('root/cache/Request/FindHats.php')->url())); $actualFindHats = eval('return new \\ServiceTest\\Hatstore\\Request\\FindHats();'); @@ -150,7 +162,11 @@ public function cachesProcessorsFromPetStoreExpanded( ): void { $cacheDir = $this->root->url() . '/cache'; - $this->sut->cache($openAPIFilePath, $cacheDir, $namespace); + $this->sut->cache( + $openAPIFilePath, + $cacheDir, + $namespace, + ); $fullClassName = sprintf('\\%s\\%s', $namespace, $className); @@ -170,7 +186,7 @@ public function cacheOnlyRequestProcessors(): void $cacheDir, 'ServiceTest\\Petstore\\RequestsOnly', true, - false + false, ); self::assertDirectoryDoesNotExist("$cacheDir/Response"); @@ -190,7 +206,6 @@ public function cacheOnlyResponseProcessors(): void $cacheDir, 'ServiceTest\\Petstore\\ResponsesOnly', false, - true ); self::assertDirectoryExists("$cacheDir/Response"); diff --git a/tests/Console/Template/RequestBuilderTest.php b/tests/Console/Template/RequestBuilderTest.php index d309ec86..b0564dfd 100644 --- a/tests/Console/Template/RequestBuilderTest.php +++ b/tests/Console/Template/RequestBuilderTest.php @@ -31,6 +31,7 @@ class RequestBuilderTest extends TestCase public function createFromTemplateReturnsPHPString(): \RequestBuilderTemplateTest\Petstore\CachedRequestBuilder { $namespace = 'RequestBuilderTemplateTest\\Petstore'; + $classname = 'CachedRequestBuilder'; $petstoreExpandedFilePath = $this->petstoreAPIPath; $map = [ 'findPets' => 'RequestBuilderTemplateTest\\Petstore\\Request\\FindPets', @@ -39,20 +40,25 @@ public function createFromTemplateReturnsPHPString(): \RequestBuilderTemplateTes 'deletePet' => 'RequestBuilderTemplateTest\\Petstore\\Request\\DeletePet', ]; - $sut = new Template\RequestBuilder($namespace, $petstoreExpandedFilePath, $map); + $sut = new Template\RequestBuilder( + $namespace, + $classname, + $petstoreExpandedFilePath, + $map, + ); $phpString = $sut->getCode(); eval('//' . $phpString); - $openAPI = (new MembraneReader([OpenAPIVersion::Version_3_0])) + $openAPI = new MembraneReader([OpenAPIVersion::Version_3_0]) ->readFromAbsoluteFilePath($petstoreExpandedFilePath); - $routeCollection = (new RouteCollector()) - ->collect($openAPI); + $routeCollection = new RouteCollector()->collect($openAPI); $createdBuilder = eval( sprintf( - 'return new \\%s\\CachedRequestBuilder(new %s(new %s(%s)));', + 'return new \\%s\\%s(new %s(new %s(%s)));', $namespace, + $classname, Router::class, RouteCollection::class, var_export($routeCollection->routes, true) @@ -91,11 +97,11 @@ public function templatedBuilderCanBuildCachedProcessors( namespace RequestBuilderTemplateTest\Petstore\Request; use Membrane; - + class FindPets implements Membrane\Processor { public readonly Membrane\Processor $processor; - + public function __construct() { $this->processor = new Membrane\Processor\Field(\'\'); diff --git a/tests/Console/Template/ResponseBuilderTest.php b/tests/Console/Template/ResponseBuilderTest.php index 6ad0ad53..ff883ee0 100644 --- a/tests/Console/Template/ResponseBuilderTest.php +++ b/tests/Console/Template/ResponseBuilderTest.php @@ -25,12 +25,14 @@ #[UsesClass(Field::class)] class ResponseBuilderTest extends TestCase { - private $petstoreAPIPath = __DIR__ . '/../../fixtures/OpenAPI/docs/petstore-expanded.json'; + private string $petstoreAPIPath = __DIR__ . '/../../fixtures/OpenAPI/docs/petstore-expanded.json'; #[Test, TestDox('createFromTemplate will return a string of PHP code that can evaluate to a CachedResponseBuilder')] public function createFromTemplateReturnsPHPString(): \ResponseBuilderTemplateTest\Petstore\CachedResponseBuilder { $namespace = 'ResponseBuilderTemplateTest\\Petstore'; + $classname = 'CachedResponseBuilder'; + $petstoreExpandedFilePath = $this->petstoreAPIPath; $map = [ 'findPets' => [ @@ -50,18 +52,24 @@ public function createFromTemplateReturnsPHPString(): \ResponseBuilderTemplateTe ], ]; - $sut = new Template\ResponseBuilder($namespace, $petstoreExpandedFilePath, $map); + $sut = new Template\ResponseBuilder( + $namespace, + $classname, + $petstoreExpandedFilePath, + $map, + ); $phpString = $sut->getCode(); eval('//' . $phpString); - $openAPI = (new MembraneReader([OpenAPIVersion::Version_3_0])) + $openAPI = new MembraneReader([OpenAPIVersion::Version_3_0]) ->readFromAbsoluteFilePath($petstoreExpandedFilePath); - $routeCollection = (new RouteCollector())->collect($openAPI); + $routeCollection = new RouteCollector()->collect($openAPI); $createdBuilder = eval( sprintf( - 'return new \\%s\\CachedResponseBuilder(new %s(new %s(%s)));', + 'return new \\%s\\%s(new %s(new %s(%s)));', $namespace, + $classname, Router::class, RouteCollection::class, var_export($routeCollection->routes, true) @@ -102,11 +110,11 @@ public function templatedBuilderCanBuildCachedProcessors( namespace ResponseBuilderTemplateTest\Petstore\Response\Code200; use Membrane; - + class FindPets implements Membrane\Processor { public readonly Membrane\Processor $processor; - + public function __construct() { $this->processor = new Membrane\Processor\Field(\'\'); diff --git a/tests/Console/Template/RouteMatchBuilderTest.php b/tests/Console/Template/RouteMatchBuilderTest.php new file mode 100644 index 00000000..d3e808c7 --- /dev/null +++ b/tests/Console/Template/RouteMatchBuilderTest.php @@ -0,0 +1,120 @@ +petstoreAPIPath; + $map = [ + 'findPets' => 'TemplateTest\\Petstore\\Request\\FindPets', + 'addPet' => 'TemplateTest\\Petstore\\Request\\AddPet', + 'find pet by id' => 'TemplateTest\\Petstore\\Request\\FindPetById', + 'deletePet' => 'TemplateTest\\Petstore\\Request\\DeletePet', + ]; + + $sut = new Template\RouteMatchBuilder( + $namespace, + $classname, + $petstoreExpandedFilePath, + $map, + ); + eval('//' . $sut->getCode()); + + $createdBuilder = eval(sprintf( + 'return new \\%s\\%s();', + $namespace, + $classname, + )); + + self::assertInstanceOf('\TemplateTest\Petstore\CachedRouteMatchBuilder', $createdBuilder); + + return $createdBuilder; + } + + #[Test, TestDox('It can support cached processors by searching for them in the map')] + #[Depends('createFromTemplateReturnsPHPString')] + public function templatedBuilderCanSupportCachedProcessors( + \TemplateTest\Petstore\CachedRouteMatchBuilder $cachedRouteMatchBuilder + ): RouteMatch { + $routeMatch = new RouteMatch('findPets', $this->petstoreAPIPath); + + self::assertTrue($cachedRouteMatchBuilder->supports($routeMatch)); + + return $routeMatch; + } + + #[Test, TestDox('It can build cached processors by searching for them in the map')] + #[Depends('createFromTemplateReturnsPHPString'), Depends('templatedBuilderCanSupportCachedProcessors')] + public function templatedBuilderCanBuildCachedProcessors( + \TemplateTest\Petstore\CachedRouteMatchBuilder $cachedRouteMatchBuilder, + RouteMatch $routeMatch, + ): void { + eval(<<<'PHP' +namespace TemplateTest\Petstore\Request; + +use Membrane; + +class FindPets implements Membrane\Processor +{ + public readonly Membrane\Processor $processor; + + public function __construct() + { + $this->processor = new Membrane\Processor\Field(''); + } + + public function processes(): string + { + return $this->processor->processes(); + } + + public function process(Membrane\Result\FieldName $parentFieldName, mixed $value): Membrane\Result\Result + { + return $this->processor->process($parentFieldName, $value); + } + + public function __toString() + { + return (string)$this->processor; + } + + public function __toPHP(): string + { + return $this->processor->__toPHP(); + } +} +PHP); + + $processor = $cachedRouteMatchBuilder->build($routeMatch); + + self::assertInstanceOf('\\TemplateTest\\Petstore\\Request\\FindPets', $processor); + } +} From ddc7ad5f4c4ce331c37f55850cb25adb37de2b30 Mon Sep 17 00:00:00 2001 From: John Charman Date: Fri, 25 Sep 2026 11:17:53 +0100 Subject: [PATCH 9/9] Appease our lord PHPStan --- src/Console/Command/CacheOpenAPIProcessors.php | 2 -- src/Console/Service/YieldsProcessors.php | 10 ++++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Console/Command/CacheOpenAPIProcessors.php b/src/Console/Command/CacheOpenAPIProcessors.php index a620474c..103b4eb2 100644 --- a/src/Console/Command/CacheOpenAPIProcessors.php +++ b/src/Console/Command/CacheOpenAPIProcessors.php @@ -78,8 +78,6 @@ protected function configure(): void 'Use RouteMatch Builder for multi-file request handling', null, ); - - } protected function execute(InputInterface $input, OutputInterface $output): int diff --git a/src/Console/Service/YieldsProcessors.php b/src/Console/Service/YieldsProcessors.php index 22bb41ec..4efc4796 100644 --- a/src/Console/Service/YieldsProcessors.php +++ b/src/Console/Service/YieldsProcessors.php @@ -19,8 +19,8 @@ final class YieldsProcessors private Internal\Response $responseBuilder; /** @var array, + * request: string, + * response: array, * }> */ private(set) array $classMap; @@ -48,7 +48,7 @@ public function __invoke(): \Generator $classNames[$operationId] = $className = $this->createSuitableClassName($operationId, $classNames); - $this->classMap[$operationId] = [ + $operationMap = [ 'request' => $this->getRequestFQCN($className), 'response' => [], ]; @@ -72,7 +72,7 @@ public function __invoke(): \Generator foreach ($operation->responses as $code => $response) { $prefixedCode = 'Code' . ucwords((string) $code); - $this->classMap[$operationId]['responses'] []= $this + $operationMap['response'][] = $this ->getResponseFQCN($prefixedCode, $className); $this->logger @@ -85,6 +85,8 @@ public function __invoke(): \Generator ); } } + + $this->classMap[$operationId] = $operationMap; } } }