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/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", diff --git a/src/Console/Command/CacheOpenAPIProcessors.php b/src/Console/Command/CacheOpenAPIProcessors.php index 2946031c..103b4eb2 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, @@ -54,6 +70,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 +92,33 @@ protected function execute(InputInterface $input, OutputInterface $output): int assert(is_bool($skipResponses)); $skipRequests = $input->getOption('skip-requests'); assert(is_bool($skipRequests)); + $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); 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 = new Service\CacheOpenAPIProcessors($consoleLogger) + ->cache( + $openAPIFilePath, + $destination, + $namespace, + !$skipRequests, + !$skipResponses, + $routeMatch, + $requestName, + $responseName, + ); - $success = $cachingService->cache($openAPIFilePath, $destination, $namespace, !$skipRequests, !$skipResponses); return $success ? Command::SUCCESS : Command::FAILURE; } } diff --git a/src/Console/Service/CacheOpenAPIProcessors.php b/src/Console/Service/CacheOpenAPIProcessors.php index 321b4aac..059795f9 100644 --- a/src/Console/Service/CacheOpenAPIProcessors.php +++ b/src/Console/Service/CacheOpenAPIProcessors.php @@ -6,11 +6,10 @@ 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; -use Membrane\OpenAPIReader\MembraneReader; -use Membrane\OpenAPIReader\OpenAPIVersion; use Psr\Log\LoggerInterface; class CacheOpenAPIProcessors @@ -25,17 +24,61 @@ public function cache( string $cacheDestinationFilePath, string $cacheNamespace, bool $buildRequests = true, - bool $buildResponses = true + bool $buildResponses = true, + 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, - )); + $definitionProducer = new PHPClassDefinitionProducer($gensClasses()); $destination = rtrim($cacheDestinationFilePath, '/'); $classWriter = new PHPFilesWriter($destination, $cacheNamespace); diff --git a/src/Console/Service/YieldsClassDefinitions.php b/src/Console/Service/YieldsClassDefinitions.php deleted file mode 100644 index 11d626f7..00000000 --- a/src/Console/Service/YieldsClassDefinitions.php +++ /dev/null @@ -1,151 +0,0 @@ -readOpenAPIFile($openAPIFilePath); - - // Initialize classMap for CachedBuilers - $classNames = []; - $classMap = []; - - foreach ($openAPI->paths as $pathUrl => $path) { - foreach ($path->getOperations() as $method => $operation) { - $methodObject = Method::from(strtolower($method)); - $operationId = $operation->operationId; - - $classNames[$operationId] = $className = - $this->createSuitableClassName($operationId, $classNames); - $classMap[$operationId] = [ - 'request' => "$cacheNamespace\\Request\\$className", - 'response' => [], - ]; - - if ($buildRequests) { - $this->logger->info( - "Generating $cacheNamespace\\Request\\$className" - ); - - yield new Template\Processor( - namespace: "$cacheNamespace\\Request", - name: $className, - processor: $this->getRequestBuilder()->build( - new PathParameterExtractor($pathUrl), - $path, - $methodObject, - ) - ); - } - - if ($buildResponses) { - foreach ($operation->responses as $code => $response) { - $prefixedCode = 'Code' . ucwords((string) $code); - $this->logger->info( - "Generating $cacheNamespace\\Response\\$prefixedCode\\$className" - ); - - yield new Template\Processor( - namespace: "$cacheNamespace\\Response\\$prefixedCode", - name: $className, - processor: $this->getResponseBuilder()->build($response), - ); - } - } - } - - if ($buildRequests) { - yield new Template\RequestBuilder( - "$cacheNamespace", - $openAPIFilePath, - array_map(fn($p) => $p['request'], $classMap), - ); - } - - if ($buildResponses) { - yield new Template\ResponseBuilder( - "$cacheNamespace", - $openAPIFilePath, - array_map(fn($p) => $p['response'], $classMap), - ); - } - } - } - - private function readOpenAPIFile(string $filepath): V30\OpenAPI | V31\OpenAPI - { - $this->logger->info("Reading OpenAPI from $filepath"); - return new MembraneReader([ - OpenAPIVersion::Version_3_0, - OpenAPIVersion::Version_3_1 - ])->readFromAbsoluteFilePath($filepath); - } - - /** @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; - - assert(is_string($alphanumericName)); - if (is_numeric($alphanumericName[0])) { - $alphanumericName = 'm' . $alphanumericName; - } - - if (in_array($alphanumericName, $existingClassNames)) { - $i = 1; - do { - $postfixedName = sprintf('%s%d', $alphanumericName, $i++); - } while (in_array($postfixedName, $existingClassNames)); - - return $postfixedName; - } - - return $alphanumericName; - } - - - private function getRequestBuilder(): Request - { - if (!isset($this->requestBuilder)) { - $this->requestBuilder = new Request(); - return $this->requestBuilder; - } - - return $this->requestBuilder; - } - - private function getResponseBuilder(): Response - { - if (!isset($this->responseBuilder)) { - $this->responseBuilder = new Response(); - return $this->responseBuilder; - } - return $this->responseBuilder; - } -} diff --git a/src/Console/Service/YieldsProcessors.php b/src/Console/Service/YieldsProcessors.php new file mode 100644 index 00000000..4efc4796 --- /dev/null +++ b/src/Console/Service/YieldsProcessors.php @@ -0,0 +1,156 @@ +, + * }> + */ + private(set) array $classMap; + + public function __construct( + private readonly LoggerInterface $logger, + private readonly string $apiFilePath, + private readonly string $cacheNamespace, + private readonly bool $buildRequests, + private readonly bool $buildResponses, + ) { + } + + public function __invoke(): \Generator + { + $this->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)); + $operationId = $operation->operationId; + + $classNames[$operationId] = $className = + $this->createSuitableClassName($operationId, $classNames); + $operationMap = [ + 'request' => $this->getRequestFQCN($className), + 'response' => [], + ]; + + if ($this->buildRequests) { + $this->logger + ->info("Generating {$this->getRequestFQCN($className)}"); + + yield new Template\Processor( + namespace: $this->getRequestNamespace(), + name: $className, + processor: $this->getRequestBuilder()->build( + new PathParameterExtractor($pathUrl), + $path, + $methodObject, + ), + ); + } + + if ($this->buildResponses) { + foreach ($operation->responses as $code => $response) { + $prefixedCode = 'Code' . ucwords((string) $code); + + $operationMap['response'][] = $this + ->getResponseFQCN($prefixedCode, $className); + + $this->logger + ->info("Generating {$this->getResponseFQCN($prefixedCode, $className)}"); + + yield new Template\Processor( + namespace: $this->getResponseNamespace($prefixedCode), + name: $className, + processor: $this->getResponseBuilder()->build($response), + ); + } + } + + $this->classMap[$operationId] = $operationMap; + } + } + } + + private function getRequestNamespace(): string + { + return "{$this->cacheNamespace}\\Request"; + } + + private function getRequestFQCN(string $name): string + { + return "{$this->getRequestNamespace()}\\{$name}"; + } + + 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 + { + $this->logger->info("Reading OpenAPI from $filepath"); + return new MembraneReader([ + OpenAPIVersion::Version_3_0, + OpenAPIVersion::Version_3_1 + ])->readFromAbsoluteFilePath($filepath); + } + + /** @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; + assert(is_string($alphanumericName)); + + if (is_numeric($alphanumericName[0])) { + $alphanumericName = 'm' . $alphanumericName; + } + + if (in_array($alphanumericName, $existingClassNames, true)) { + $i = 1; + do { + $postfixedName = sprintf('%s%d', $alphanumericName, $i++); + } while (in_array($postfixedName, $existingClassNames, true)); + + return $postfixedName; + } + + return $alphanumericName; + } + + + private function getRequestBuilder(): Internal\Request + { + return $this->requestBuilder ??= new Internal\Request(); + } + + private function getResponseBuilder(): Internal\Response + { + return $this->responseBuilder ??= new Internal\Response(); + } +} 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 new file mode 100644 index 00000000..b324c25f --- /dev/null +++ b/src/Console/Template/RouteMatchBuilder.php @@ -0,0 +1,83 @@ +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, + ); + } +} 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, + ); + } +} 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); + } +}