diff --git a/README.md b/README.md index a634eb6..e7bc21f 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ The preferred way to install this extension is through [composer](http://getcomp Run ``` -composer require cebe/php-openapi:dev-php-81-compat onmoon/openapi-server-bundle +composer require onmoon/openapi-server-bundle ``` Then add the bundle class to your `config/bundles.php`: diff --git a/composer.json b/composer.json index edc81f4..cb3dca3 100644 --- a/composer.json +++ b/composer.json @@ -24,10 +24,10 @@ "require": { "php": "^8.1", "ext-json": "*", - "devizzent/cebe-php-openapi": "1.1.4", + "devizzent/cebe-php-openapi": "^1.1.4", "league/openapi-psr7-validator": "^0.22.0", "lukasoppermann/http-status": "^4.0", - "nikic/php-parser": "^v5.4", + "nikic/php-parser": "^4.19|^v5.0", "nyholm/psr7": "^1.5", "phpdocumentor/reflection-docblock": "^5.3", "sspat/reserved-words": "^3.0", @@ -41,23 +41,23 @@ "symfony/psr-http-message-bridge": "^6.4|^7.0", "symfony/routing": "^6.4|^7.0", "symfony/yaml": "^6.4|^7.0", - "thecodingmachine/safe": "^3.1" + "thecodingmachine/safe": "^1.3|^2|^3.1" }, "require-dev": { "doctrine/coding-standard": "^12.0", "matthiasnoback/symfony-config-test": "^5.1", "matthiasnoback/symfony-dependency-injection-test": "^5.1", - "phpstan/phpstan": "^2.1", - "phpstan/phpstan-phpunit": "^2.0", - "phpstan/phpstan-strict-rules": "^2.0", + "phpstan/phpstan": "^1.11|^2.1", + "phpstan/phpstan-phpunit": "^1.4|^2.0", + "phpstan/phpstan-strict-rules": "^1.6|^2.0", "phpunit/phpunit": "^10.5", - "roave/infection-static-analysis-plugin": "^1.37", + "roave/infection-static-analysis-plugin": "^1.35", "squizlabs/php_codesniffer": "^3.10", "symfony/browser-kit": "^6.4|^7.0", "symfony/dom-crawler": "^6.4|^7.0", "symfony/framework-bundle": "^6.4|^7.0", - "thecodingmachine/phpstan-safe-rule": "v1.4", - "vimeo/psalm": "^6.10" + "thecodingmachine/phpstan-safe-rule": "^1.2|v1.4", + "vimeo/psalm": "^5.24|^6.10" }, "minimum-stability": "stable", "prefer-stable": true, diff --git a/phpstan.neon b/phpstan.neon index 2cc69f0..0045c6b 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -30,10 +30,6 @@ parameters: message: '#Method OnMoon\\OpenApiServerBundle\\Specification\\SpecificationParser::getResponseDtoDefinitions\(\) has parameter \$responses with no value type specified in iterable type array\.#' paths: - %currentWorkingDirectory%/src/Specification/SpecificationParser.php - - - message: '#Parameter \#1 \$json of function Safe\\json_decode expects string, resource\|string given\.#' - paths: - - %currentWorkingDirectory%/src/Serializer/ArrayDtoSerializer.php includes: - vendor/thecodingmachine/phpstan-safe-rule/phpstan-safe-rule.neon - vendor/phpstan/phpstan-phpunit/extension.neon diff --git a/psalm.xml b/psalm.xml index 970e114..e9a4f81 100644 --- a/psalm.xml +++ b/psalm.xml @@ -7,6 +7,7 @@ findUnusedVariablesAndParams="true" ensureArrayStringOffsetsExist="true" findUnusedBaselineEntry="true" + ensureOverrideAttribute="false" findUnusedCode="false" phpVersion="8.1" > @@ -19,25 +20,8 @@ - - - - - - - - - - - - - - - - - diff --git a/src/CodeGenerator/Definitions/ClassDefinition.php b/src/CodeGenerator/Definitions/ClassDefinition.php index 6f226b5..775fe0e 100644 --- a/src/CodeGenerator/Definitions/ClassDefinition.php +++ b/src/CodeGenerator/Definitions/ClassDefinition.php @@ -4,8 +4,6 @@ namespace OnMoon\OpenApiServerBundle\CodeGenerator\Definitions; -use Override; - use function strrpos; use function substr; @@ -14,7 +12,6 @@ class ClassDefinition implements ClassReference private string $className; private string $namespace; - #[Override] final public function getClassName(): string { return $this->className; @@ -27,7 +24,6 @@ final public function setClassName(string $className): self return $this; } - #[Override] final public function getNamespace(): string { return $this->namespace; @@ -40,7 +36,6 @@ final public function setNamespace(string $namespace): self return $this; } - #[Override] final public function getFQCN(): string { return $this->namespace . '\\' . $this->className; diff --git a/src/CodeGenerator/Definitions/ComponentReference.php b/src/CodeGenerator/Definitions/ComponentReference.php index d25b4f9..0161942 100644 --- a/src/CodeGenerator/Definitions/ComponentReference.php +++ b/src/CodeGenerator/Definitions/ComponentReference.php @@ -4,33 +4,27 @@ namespace OnMoon\OpenApiServerBundle\CodeGenerator\Definitions; -use Override; - final class ComponentReference implements DtoReference { public function __construct(private ComponentDefinition $referencedComponent) { } - #[Override] public function getClassName(): string { return $this->referencedComponent->getDto()->getClassName(); } - #[Override] public function getNamespace(): string { return $this->referencedComponent->getDto()->getNamespace(); } - #[Override] public function getFQCN(): string { return $this->referencedComponent->getDto()->getFQCN(); } - #[Override] public function isEmpty(): bool { return $this->referencedComponent->getDto()->isEmpty(); diff --git a/src/CodeGenerator/Definitions/DtoDefinition.php b/src/CodeGenerator/Definitions/DtoDefinition.php index 7c0bcb6..9fe087a 100644 --- a/src/CodeGenerator/Definitions/DtoDefinition.php +++ b/src/CodeGenerator/Definitions/DtoDefinition.php @@ -5,7 +5,6 @@ namespace OnMoon\OpenApiServerBundle\CodeGenerator\Definitions; use OnMoon\OpenApiServerBundle\Interfaces\Dto; -use Override; use function count; @@ -22,7 +21,6 @@ public function __construct(array $properties) $this->properties = $properties; } - #[Override] final public function isEmpty(): bool { return count($this->properties) === 0; diff --git a/src/CodeGenerator/Filesystem/FilePutContentsFileWriter.php b/src/CodeGenerator/Filesystem/FilePutContentsFileWriter.php index d10065a..beb97ba 100644 --- a/src/CodeGenerator/Filesystem/FilePutContentsFileWriter.php +++ b/src/CodeGenerator/Filesystem/FilePutContentsFileWriter.php @@ -4,8 +4,6 @@ namespace OnMoon\OpenApiServerBundle\CodeGenerator\Filesystem; -use Override; - use function is_dir; use function Safe\file_put_contents; use function Safe\mkdir; @@ -21,7 +19,6 @@ public function __construct(int $dirPemissions) $this->dirPemissions = $dirPemissions; } - #[Override] public function write(string $path, string $filename, string $contents): void { if (! is_dir($path)) { diff --git a/src/CodeGenerator/Naming/DefaultNamingStrategy.php b/src/CodeGenerator/Naming/DefaultNamingStrategy.php index 233b0b9..76b5b4a 100644 --- a/src/CodeGenerator/Naming/DefaultNamingStrategy.php +++ b/src/CodeGenerator/Naming/DefaultNamingStrategy.php @@ -7,7 +7,6 @@ use OnMoon\OpenApiServerBundle\CodeGenerator\NameGenerator; // phpcs:ignore SlevomatCodingStandard.Namespaces.UnusedUses.UnusedUse use OnMoon\OpenApiServerBundle\Interfaces\RequestHandler; -use Override; use sspat\ReservedWords\ReservedWords; use function array_map; @@ -38,13 +37,11 @@ public function __construct( $this->languageLevel = $languageLevel; } - #[Override] public function isAllowedPhpPropertyName(string $name): bool { return preg_match('/^\d/', $name) === 0 && preg_match('/^[A-Za-z0-9_]+$/', $name) === 1; } - #[Override] public function getInterfaceFQCN(string $apiNameSpace, string $operationId): string { /** @psalm-var class-string $interfaceNamespace */ @@ -59,7 +56,6 @@ public function getInterfaceFQCN(string $apiNameSpace, string $operationId): str return $interfaceNamespace; } - #[Override] public function stringToNamespace(string $text): string { $namespace = $this->padStringThatIsReservedNamespaceName( @@ -75,7 +71,6 @@ public function stringToNamespace(string $text): string return $namespace; } - #[Override] public function stringToMethodName(string $text): string { $propertyName = $this->padStringThatIsReservedMethodName( @@ -93,13 +88,11 @@ public function stringToMethodName(string $text): string return $propertyName; } - #[Override] public function buildNamespace(string ...$parts): string { return implode('\\', array_map(static fn (string $part): string => trim($part, '\\'), $parts)); } - #[Override] public function buildPath(string ...$parts): string { return implode( diff --git a/src/CodeGenerator/PhpParserGenerators/DtoCodeGenerator.php b/src/CodeGenerator/PhpParserGenerators/DtoCodeGenerator.php index 2b47970..6903afb 100644 --- a/src/CodeGenerator/PhpParserGenerators/DtoCodeGenerator.php +++ b/src/CodeGenerator/PhpParserGenerators/DtoCodeGenerator.php @@ -160,9 +160,10 @@ private function generateClassProperty(FileBuilder $builder, PropertyDefinition $property->setType($this->getTypePhp($builder, $definition)); $docCommentLines = []; + $description = $definition->getDescription(); - if ($definition->getDescription() !== null) { - $docCommentLines[] = sprintf('%s', $definition->getDescription()); + if ($description !== null) { + $docCommentLines[] = sprintf('%s', $description); $docCommentLines[] = ''; } diff --git a/src/CodeGenerator/PhpParserGenerators/ServiceSubscriberCodeGenerator.php b/src/CodeGenerator/PhpParserGenerators/ServiceSubscriberCodeGenerator.php index fbcbeb7..4119ef5 100644 --- a/src/CodeGenerator/PhpParserGenerators/ServiceSubscriberCodeGenerator.php +++ b/src/CodeGenerator/PhpParserGenerators/ServiceSubscriberCodeGenerator.php @@ -69,7 +69,9 @@ public function generate(GraphDefinition $graphDefinition): GeneratedFileDefinit } else { foreach ($operation->getResponses() as $response) { $responseTypes[] = new ArrayItem( + // @codeCoverageIgnoreStart new Array_([new ArrayItem(new String_($response->getStatusCode()))], ['kind' => Array_::KIND_SHORT]), + // @codeCoverageIgnoreEnd new ClassConstFetch( new Name($fileBuilder->getReference($response->getResponseBody())), 'class' @@ -79,7 +81,9 @@ public function generate(GraphDefinition $graphDefinition): GeneratedFileDefinit } $responseCodeMapper[] = new ArrayItem( + // @codeCoverageIgnoreStart new Array_($responseTypes, ['kind' => Array_::KIND_SHORT]), + // @codeCoverageIgnoreEnd new ClassConstFetch( new Name($fileBuilder->getReference($operation->getRequestHandlerInterface())), 'class' @@ -90,7 +94,9 @@ public function generate(GraphDefinition $graphDefinition): GeneratedFileDefinit $httpCodeMapper = $this ->factory + // @codeCoverageIgnoreStart ->classConst('HTTP_CODES', new Array_($responseCodeMapper, ['kind' => Array_::KIND_SHORT])) + // @codeCoverageIgnoreEnd ->makePrivate(); $property = $this @@ -125,6 +131,7 @@ public function generate(GraphDefinition $graphDefinition): GeneratedFileDefinit ->setDocComment('/** * @inheritDoc */') + // @codeCoverageIgnoreStart ->addStmt( new Return_( new Array_( @@ -133,6 +140,7 @@ public function generate(GraphDefinition $graphDefinition): GeneratedFileDefinit ) ) ); + // @codeCoverageIgnoreEnd $getRequestHandler = $this ->factory diff --git a/src/Command/DeleteGeneratedCodeCommand.php b/src/Command/DeleteGeneratedCodeCommand.php index 23d1f2b..05fac36 100644 --- a/src/Command/DeleteGeneratedCodeCommand.php +++ b/src/Command/DeleteGeneratedCodeCommand.php @@ -4,7 +4,7 @@ namespace OnMoon\OpenApiServerBundle\Command; -use Override; +use FilesystemIterator; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use SplFileInfo; @@ -43,7 +43,6 @@ public function __construct(string $rootPath, ?string $name = null) */ protected static $defaultName = self::COMMAND; - #[Override] protected function configure(): void { $this @@ -55,7 +54,6 @@ protected function configure(): void ); } - #[Override] protected function execute(InputInterface $input, OutputInterface $output): int { if (! (bool) $input->getOption('yes')) { @@ -86,15 +84,15 @@ private function recursiveDelete(string $directoryPath): void return; } - /** @var SplFileInfo[] $iterator */ $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $directoryPath, - RecursiveDirectoryIterator::SKIP_DOTS + FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::CHILD_FIRST ); + /** @var SplFileInfo $directoryOrFile */ foreach ($iterator as $directoryOrFile) { if ($directoryOrFile->isDir()) { rmdir($directoryOrFile->getPathname()); diff --git a/src/Command/GenerateApiCodeCommand.php b/src/Command/GenerateApiCodeCommand.php index f32dbd0..d0db4f0 100644 --- a/src/Command/GenerateApiCodeCommand.php +++ b/src/Command/GenerateApiCodeCommand.php @@ -7,7 +7,6 @@ use FilesystemIterator; use OnMoon\OpenApiServerBundle\CodeGenerator\ApiServerCodeGenerator; use OnMoon\OpenApiServerBundle\Specification\SpecificationLoader; -use Override; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use SplFileInfo; @@ -47,7 +46,6 @@ public function __construct( parent::__construct($name); } - #[Override] protected function configure(): void { $this @@ -67,7 +65,6 @@ protected function configure(): void */ protected static $defaultName = self::COMMAND; - #[Override] protected function execute(InputInterface $input, OutputInterface $output): int { $keep = (bool) $input->getOption('keep'); @@ -100,7 +97,7 @@ private function removeExtraFiles(string $root, array $generatedFiles): void RecursiveIteratorIterator::CHILD_FIRST ); - /** @var SplFileInfo[] $iterator */ + /** @var SplFileInfo $directoryOrFile */ foreach ($iterator as $directoryOrFile) { if ($directoryOrFile->isDir() || in_array($directoryOrFile->getPathname(), $generatedFiles, true)) { continue; diff --git a/src/DependencyInjection/CompilerPass.php b/src/DependencyInjection/CompilerPass.php index 0fa329a..a29636a 100644 --- a/src/DependencyInjection/CompilerPass.php +++ b/src/DependencyInjection/CompilerPass.php @@ -5,7 +5,6 @@ namespace OnMoon\OpenApiServerBundle\DependencyInjection; use OnMoon\OpenApiServerBundle\Controller\ApiController; -use Override; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; @@ -21,7 +20,6 @@ public function __construct(string $tag) $this->tag = $tag; } - #[Override] public function process(ContainerBuilder $container): void { if (! $container->has(ApiController::class)) { diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index 9424a6d..148487e 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -4,13 +4,11 @@ namespace OnMoon\OpenApiServerBundle\DependencyInjection; -use Override; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; final class Configuration implements ConfigurationInterface { - #[Override] public function getConfigTreeBuilder(): TreeBuilder { $treeBuilder = new TreeBuilder('open_api_server'); diff --git a/src/DependencyInjection/OpenApiServerExtension.php b/src/DependencyInjection/OpenApiServerExtension.php index 23a7a57..416633d 100644 --- a/src/DependencyInjection/OpenApiServerExtension.php +++ b/src/DependencyInjection/OpenApiServerExtension.php @@ -6,7 +6,6 @@ use Exception; use OnMoon\OpenApiServerBundle\Specification\SpecificationLoader; -use Override; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Extension\Extension; @@ -20,7 +19,6 @@ final class OpenApiServerExtension extends Extension implements ExtensionInterface { /** @param mixed[] $configs */ - #[Override] public function load(array $configs, ContainerBuilder $container): void { $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); diff --git a/src/Exception/CannotParseOpenApi.php b/src/Exception/CannotParseOpenApi.php index d2036e1..fd2c626 100644 --- a/src/Exception/CannotParseOpenApi.php +++ b/src/Exception/CannotParseOpenApi.php @@ -82,6 +82,21 @@ public static function becauseOnlyScalarAreAllowed(string $propertyName, array $ ); } + /** @param array{location:string,method:string,url:string,path:string} $context */ + public static function becauseOpenapi31TypesNotSupported(string $propertyName, array $context): self + { + return new self( + sprintf( + 'Cannot generate property for DTO class, property "%s" has multiple types in %s for operation: "%s" of path: "%s" in specification file: "%s".', + $propertyName, + $context['location'], + $context['method'], + $context['url'], + $context['path'] + ) + ); + } + /** @param array{location:string,method:string,url:string,path:string} $context */ public static function becauseArrayIsNotDescribed(string $propertyName, array $context): self { diff --git a/src/OpenApiServerBundle.php b/src/OpenApiServerBundle.php index 0cbc82a..7a9839b 100644 --- a/src/OpenApiServerBundle.php +++ b/src/OpenApiServerBundle.php @@ -6,7 +6,6 @@ use OnMoon\OpenApiServerBundle\DependencyInjection\CompilerPass; use OnMoon\OpenApiServerBundle\Interfaces\ApiLoader; -use Override; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; @@ -14,7 +13,6 @@ final class OpenApiServerBundle extends Bundle { public const API_LOADER_TAG = 'openapi.api_loader'; - #[Override] public function build(ContainerBuilder $container): void { $container->registerForAutoconfiguration(ApiLoader::class)->addTag(self::API_LOADER_TAG); diff --git a/src/Router/RouteLoader.php b/src/Router/RouteLoader.php index b33a928..9b30a7a 100644 --- a/src/Router/RouteLoader.php +++ b/src/Router/RouteLoader.php @@ -7,7 +7,6 @@ use OnMoon\OpenApiServerBundle\Controller\ApiController; use OnMoon\OpenApiServerBundle\Specification\SpecificationLoader; use OnMoon\OpenApiServerBundle\Types\ArgumentResolver; -use Override; use Stringable; use Symfony\Component\Config\Loader\Loader; use Symfony\Component\Routing\Route; @@ -30,7 +29,6 @@ public function __construct(SpecificationLoader $loader, ArgumentResolver $argum $this->argumentResolver = $argumentResolver; } - #[Override] public function load(mixed $resource, ?string $type = null): RouteCollection { $specName = (string) $resource; @@ -44,14 +42,7 @@ public function load(mixed $resource, ?string $type = null): RouteCollection $parameters = $operation->getRequestParameters(); if (array_key_exists('path', $parameters)) { - $argumentPatterns = $this->argumentResolver->resolveArgumentPatterns($parameters['path']); - foreach ($argumentPatterns as $name => $pattern) { - if ($pattern === null) { - continue; - } - - $requirements[$name] = $pattern; - } + $requirements = $this->argumentResolver->resolveArgumentPatterns($parameters['path']); } $defaults = [ @@ -70,7 +61,6 @@ public function load(mixed $resource, ?string $type = null): RouteCollection } /** @inheritDoc */ - #[Override] public function supports($resource, ?string $type = null): bool { return $type === self::OPENAPI_TYPE; diff --git a/src/Serializer/ArrayDtoSerializer.php b/src/Serializer/ArrayDtoSerializer.php index 789db2e..51ba0d8 100644 --- a/src/Serializer/ArrayDtoSerializer.php +++ b/src/Serializer/ArrayDtoSerializer.php @@ -4,17 +4,14 @@ namespace OnMoon\OpenApiServerBundle\Serializer; -use Exception; use OnMoon\OpenApiServerBundle\Interfaces\Dto; use OnMoon\OpenApiServerBundle\Specification\Definitions\ObjectSchema; use OnMoon\OpenApiServerBundle\Specification\Definitions\Operation; use OnMoon\OpenApiServerBundle\Types\ScalarTypesResolver; -use Override; use Symfony\Component\HttpFoundation\Request; use function array_key_exists; use function array_map; -use function is_resource; use function Safe\json_decode; final class ArrayDtoSerializer implements DtoSerializer @@ -28,7 +25,6 @@ public function __construct(ScalarTypesResolver $resolver, bool $sendNulls) $this->sendNotRequiredNullableNulls = $sendNulls; } - #[Override] public function createRequestDto( Request $request, Operation $operation, @@ -51,11 +47,7 @@ public function createRequestDto( $bodyType = $operation->getRequestBody(); if ($bodyType !== null) { - /** @var resource|string $source */ $source = $request->getContent(); - if (is_resource($source)) { - throw new Exception('Expecting string as contents, resource received'); - } /** @var mixed[] $rawBody */ $rawBody = json_decode($source, true); @@ -69,7 +61,6 @@ public function createRequestDto( } /** @inheritDoc */ - #[Override] public function createResponseFromDto(Dto $responseDto, ObjectSchema $definition): array { return $this->convert(false, $responseDto->toArray(), $definition); diff --git a/src/Specification/Definitions/ObjectReference.php b/src/Specification/Definitions/ObjectReference.php index c3f6cad..8fde388 100644 --- a/src/Specification/Definitions/ObjectReference.php +++ b/src/Specification/Definitions/ObjectReference.php @@ -4,8 +4,6 @@ namespace OnMoon\OpenApiServerBundle\Specification\Definitions; -use Override; - final class ObjectReference implements GetSchema { public function __construct(private string $schemaName, private ObjectSchema $referencedObject) @@ -22,7 +20,6 @@ public function getReferencedObject(): ObjectSchema return $this->referencedObject; } - #[Override] public function getSchema(): ObjectSchema { return $this->getReferencedObject(); diff --git a/src/Specification/Definitions/ObjectSchema.php b/src/Specification/Definitions/ObjectSchema.php index bbfba6a..e642b4f 100644 --- a/src/Specification/Definitions/ObjectSchema.php +++ b/src/Specification/Definitions/ObjectSchema.php @@ -4,8 +4,6 @@ namespace OnMoon\OpenApiServerBundle\Specification\Definitions; -use Override; - final class ObjectSchema implements GetSchema { /** @var Property[] $properties; */ @@ -23,7 +21,6 @@ public function getProperties(): array return $this->properties; } - #[Override] public function getSchema(): ObjectSchema { return $this; diff --git a/src/Specification/SpecificationParser.php b/src/Specification/SpecificationParser.php index 329cdab..87bbac6 100644 --- a/src/Specification/SpecificationParser.php +++ b/src/Specification/SpecificationParser.php @@ -375,8 +375,14 @@ private function getProperty( $itemProperty = $property; } - if (Type::isScalar($itemProperty->type)) { - $scalarTypeId = $this->typeResolver->findScalarType($itemProperty->type, $itemProperty->format); + $propertyType = $itemProperty->type; + + if (is_array($propertyType)) { + throw CannotParseOpenApi::becauseOpenapi31TypesNotSupported($propertyName, $exceptionContext); + } + + if (Type::isScalar($propertyType)) { + $scalarTypeId = $this->typeResolver->findScalarType($propertyType, $itemProperty->format); $propertyDefinition->setScalarTypeId($scalarTypeId); if ($this->typeResolver->isDateTime($scalarTypeId) && $this->dateTimeClass !== null) { @@ -398,7 +404,7 @@ private function getProperty( $propertyDefinition->setOutputType($this->dateTimeClass); } - } elseif ($itemProperty->type === Type::OBJECT) { + } elseif ($propertyType === Type::OBJECT) { $objectType = $this->getObjectSchema( $itemProperty, $isRequest, @@ -408,7 +414,7 @@ private function getProperty( $propertyDefinition->setObjectTypeDefinition($objectType); $isScalar = false; } else { - throw CannotParseOpenApi::becauseTypeNotSupported($propertyName, $itemProperty->type, $exceptionContext); + throw CannotParseOpenApi::becauseTypeNotSupported($propertyName, $propertyType, $exceptionContext); } /** @var string|int|float|bool|null $schemaDefaultValue */ diff --git a/src/Types/ArgumentResolver.php b/src/Types/ArgumentResolver.php index 61fd5ee..4974861 100644 --- a/src/Types/ArgumentResolver.php +++ b/src/Types/ArgumentResolver.php @@ -21,7 +21,9 @@ public function __construct(ScalarTypesResolver $typesResolver) /** * @return string[] - * @psalm-return array + * @psalm-return array + * + * @psalm-suppress InvalidReturnType */ public function resolveArgumentPatterns(ObjectSchema $pathParameters): array { @@ -47,6 +49,7 @@ public function resolveArgumentPatterns(ObjectSchema $pathParameters): array } } + /** @psalm-suppress InvalidReturnStatement */ return $patterns; } } diff --git a/src/Validator/LeaguePSR7RequestSchemaValidator.php b/src/Validator/LeaguePSR7RequestSchemaValidator.php index c002046..aaefffa 100644 --- a/src/Validator/LeaguePSR7RequestSchemaValidator.php +++ b/src/Validator/LeaguePSR7RequestSchemaValidator.php @@ -7,7 +7,6 @@ use League\OpenAPIValidation\PSR7\OperationAddress; use League\OpenAPIValidation\PSR7\ValidatorBuilder; use OnMoon\OpenApiServerBundle\Specification\Definitions\Specification; -use Override; use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory; use Symfony\Component\HttpFoundation\Request; @@ -24,7 +23,6 @@ public function __construct( $this->httpFactory = $httpFactory; } - #[Override] public function validate( Request $request, Specification $specification, diff --git a/test/functional/Command/DeleteGeneratedCodeCommandTest.php b/test/functional/Command/DeleteGeneratedCodeCommandTest.php index a638d68..db5ad3a 100644 --- a/test/functional/Command/DeleteGeneratedCodeCommandTest.php +++ b/test/functional/Command/DeleteGeneratedCodeCommandTest.php @@ -9,6 +9,7 @@ use PHPUnit\Framework\Assert; use Symfony\Component\Console\Tester\CommandTester; +use function is_dir; use function rtrim; use function Safe\file_put_contents; use function Safe\mkdir; @@ -24,7 +25,10 @@ public function setUp(): void $command = $this->application->find(DeleteGeneratedCodeCommand::COMMAND); $this->commandTester = new CommandTester($command); - mkdir(TestKernel::$bundleRootPath); + if (! is_dir(TestKernel::$bundleRootPath)) { + mkdir(TestKernel::$bundleRootPath); + } + file_put_contents(TestKernel::$bundleRootPath . '/test.txt', ''); } diff --git a/test/generation/GeneratedClassAsserter.php b/test/generation/GeneratedClassAsserter.php index 780b47e..52b6770 100644 --- a/test/generation/GeneratedClassAsserter.php +++ b/test/generation/GeneratedClassAsserter.php @@ -22,8 +22,8 @@ use PhpParser\Node\Stmt\UseUse; use PhpParser\NodeFinder; use PhpParser\ParserFactory; -use PhpParser\PhpVersion; use PHPUnit\Framework\Assert; +use ReflectionClass; use function array_pop; use function explode; @@ -40,9 +40,14 @@ final class GeneratedClassAsserter public function __construct(InMemoryFileWriter $fileWriter, string $path) { $this->nodeFinder = new NodeFinder(); - $phpParser = (new ParserFactory())->createForVersion(PhpVersion::fromString('7.0')); - $phpCode = $fileWriter->getContentsByFullPath($path); - $statements = $phpParser->parse($phpCode); + if ((new ReflectionClass(ParserFactory::class))->hasMethod('create')) { + $phpParser = (new ParserFactory())->create(1); + } else { + $phpParser = (new ParserFactory())->createForHostVersion(); + } + + $phpCode = $fileWriter->getContentsByFullPath($path); + $statements = $phpParser->parse($phpCode); if ($statements === null) { throw new InvalidArgumentException('No statements found in provided PHP code'); } diff --git a/test/generation/GenerationTestCase.php b/test/generation/GenerationTestCase.php index 69cbf28..593bcf2 100644 --- a/test/generation/GenerationTestCase.php +++ b/test/generation/GenerationTestCase.php @@ -9,8 +9,8 @@ use PhpParser\NodeFinder; use PhpParser\Parser; use PhpParser\ParserFactory; -use PhpParser\PhpVersion; use PHPUnit\Framework\TestCase; +use ReflectionClass; abstract class GenerationTestCase extends TestCase { @@ -19,7 +19,12 @@ abstract class GenerationTestCase extends TestCase public function setUp(): void { - $this->phpParser = (new ParserFactory())->createForVersion(PhpVersion::fromString('7.0')); + if ((new ReflectionClass(ParserFactory::class))->hasMethod('create')) { + $this->phpParser = (new ParserFactory())->create(1); + } else { + $this->phpParser = (new ParserFactory())->createForHostVersion(); + } + $this->nodeFinder = new NodeFinder(); } diff --git a/test/unit/CodeGenerator/PhpParserGenerators/FileBuilderTest.php b/test/unit/CodeGenerator/PhpParserGenerators/FileBuilderTest.php index 0798d40..14a1948 100644 --- a/test/unit/CodeGenerator/PhpParserGenerators/FileBuilderTest.php +++ b/test/unit/CodeGenerator/PhpParserGenerators/FileBuilderTest.php @@ -13,6 +13,7 @@ use PhpParser\Node\Stmt\UseUse; use PHPUnit\Framework\Assert; use PHPUnit\Framework\TestCase; +use ReflectionClass; /** @covers \OnMoon\OpenApiServerBundle\CodeGenerator\PhpParserGenerators\FileBuilder */ class FileBuilderTest extends TestCase @@ -32,7 +33,11 @@ public function testAddStmt(): void /** @var \PhpParser\Node\Stmt\Use_ $statementToCheck */ $statementToCheck = $this->fileBuilder->getNamespace()->getNode()->stmts[0]; - Assert::assertEquals('test', $statementToCheck->uses[0]->name->name); + if ((new ReflectionClass(Name::class))->hasProperty('name')) { + Assert::assertEquals('test', $statementToCheck->uses[0]->name->name); + } else { + Assert::assertEquals('test', $statementToCheck->uses[0]->name->parts[0]); + } } public function testReferenceWithNotMatching(): void @@ -63,7 +68,13 @@ public function testReferenceWithSameDefinition(): void /** @var Name $nodeName */ $nodeName = $namespace->getNode()->name; - Assert::assertEquals('NamespaceOne\NamespaceTwo', $nodeName->name); + if ((new ReflectionClass(Name::class))->hasProperty('name')) { + Assert::assertEquals('NamespaceOne\NamespaceTwo', $nodeName->name); + } else { + Assert::assertEquals('NamespaceOne', $nodeName->parts[0]); + Assert::assertEquals('NamespaceTwo', $nodeName->parts[1]); + } + Assert::assertEquals('ClassDefinition', $reference); } diff --git a/test/unit/CodeGenerator/PhpParserGenerators/InterfaceCodeGeneratorTest.php b/test/unit/CodeGenerator/PhpParserGenerators/InterfaceCodeGeneratorTest.php index 6ac4394..bc3f255 100644 --- a/test/unit/CodeGenerator/PhpParserGenerators/InterfaceCodeGeneratorTest.php +++ b/test/unit/CodeGenerator/PhpParserGenerators/InterfaceCodeGeneratorTest.php @@ -14,6 +14,8 @@ use PHPUnit\Framework\Assert; use PHPUnit\Framework\TestCase; +use function str_replace; + /** @covers \OnMoon\OpenApiServerBundle\CodeGenerator\PhpParserGenerators\InterfaceCodeGenerator */ class InterfaceCodeGeneratorTest extends TestCase { @@ -71,7 +73,15 @@ public function test(): void; ); $generatedFileDefinition = $this->interfaceCodeGenerator->generate($generatedInterfaceDefinition); - Assert::assertEquals($expectedGeneratedFileDefinition, $generatedFileDefinition); + Assert::assertEquals( + $expectedGeneratedFileDefinition->getClass(), + $generatedFileDefinition->getClass() + ); + Assert::assertEquals( + $expectedGeneratedFileDefinition->getFileContents(), + // to support both versions of nikic/php-parser:"^4.19|^v5.0" + str_replace(') : void', '): void', $generatedFileDefinition->getFileContents()) + ); } public function testGenerateWithRequestHandlerInterfaceDefinitionAndRequestedType(): void @@ -111,7 +121,15 @@ public function test(TestClass_ $request): void; ); $generatedFileDefinition = $this->interfaceCodeGenerator->generate($generatedInterfaceDefinition); - Assert::assertEquals($expectedGeneratedFileDefinition, $generatedFileDefinition); + Assert::assertEquals( + $expectedGeneratedFileDefinition->getClass(), + $generatedFileDefinition->getClass() + ); + Assert::assertEquals( + $expectedGeneratedFileDefinition->getFileContents(), + // to support both versions of nikic/php-parser:"^4.19|^v5.0" + str_replace(') : void', '): void', $generatedFileDefinition->getFileContents()) + ); } public function testGenerateWithRequestHandlerInterfaceDefinitionAndResponseType(): void @@ -148,7 +166,15 @@ public function test(): TestClass_; ); $generatedFileDefinition = $this->interfaceCodeGenerator->generate($generatedInterfaceDefinition); - Assert::assertEquals($expectedGeneratedFileDefinition, $generatedFileDefinition); + Assert::assertEquals( + $expectedGeneratedFileDefinition->getClass(), + $generatedFileDefinition->getClass() + ); + Assert::assertEquals( + $expectedGeneratedFileDefinition->getFileContents(), + // to support both versions of nikic/php-parser:"^4.19|^v5.0" + str_replace(') : TestClass_', '): TestClass_', $generatedFileDefinition->getFileContents()) + ); } public function testGenerateWithRequestHandlerInterfaceDefinitionAndDescription(): void @@ -184,6 +210,14 @@ public function test(): void; ); $generatedFileDefinition = $this->interfaceCodeGenerator->generate($generatedInterfaceDefinition); - Assert::assertEquals($expectedGeneratedFileDefinition, $generatedFileDefinition); + Assert::assertEquals( + $expectedGeneratedFileDefinition->getClass(), + $generatedFileDefinition->getClass() + ); + Assert::assertEquals( + $expectedGeneratedFileDefinition->getFileContents(), + // to support both versions of nikic/php-parser:"^4.19|^v5.0" + str_replace(') : void', '): void', $generatedFileDefinition->getFileContents()) + ); } } diff --git a/test/unit/CodeGenerator/PhpParserGenerators/ServiceSubscriberCodeGeneratorTest.php b/test/unit/CodeGenerator/PhpParserGenerators/ServiceSubscriberCodeGeneratorTest.php index cee4328..932f893 100644 --- a/test/unit/CodeGenerator/PhpParserGenerators/ServiceSubscriberCodeGeneratorTest.php +++ b/test/unit/CodeGenerator/PhpParserGenerators/ServiceSubscriberCodeGeneratorTest.php @@ -21,6 +21,8 @@ use PhpParser\BuilderFactory; use PHPUnit\Framework\TestCase; +use function str_replace; + /** @covers \OnMoon\OpenApiServerBundle\CodeGenerator\PhpParserGenerators\ServiceSubscriberCodeGenerator */ final class ServiceSubscriberCodeGeneratorTest extends TestCase { @@ -141,6 +143,14 @@ public function getAllowedCodes(string $apiClass, string $dtoClass): array } EOD; - self::assertEquals($expectedFileContent, $result->getFileContents()); + self::assertEquals( + $expectedFileContent, + // to support both versions of nikic/php-parser:"^4.19|^v5.0" + str_replace( + [') : array', ') : ?RequestHandler'], + ['): array', '): ?RequestHandler'], + $result->getFileContents() + ) + ); } } diff --git a/test/unit/Exception/CannotParseOpenApiTest.php b/test/unit/Exception/CannotParseOpenApiTest.php index b82eaf4..ad368e6 100644 --- a/test/unit/Exception/CannotParseOpenApiTest.php +++ b/test/unit/Exception/CannotParseOpenApiTest.php @@ -109,6 +109,32 @@ public function testBecauseOnlyScalarAreAllowedShowsCorrectErrorMessage(): void throw CannotParseOpenApi::becauseOnlyScalarAreAllowed($propertyName, $context); } + public function testBecauseOpenapi31TypesNotSupportedShowsCorrectErrorMessage(): void + { + $propertyName = 'someRandomName'; + + $context = [ + 'location' => 'http://example.com', + 'method' => 'testMethod', + 'url' => 'testUrl', + 'path' => 'testPath', + ]; + + $exceptionMessage = sprintf( + 'Cannot generate property for DTO class, property "%s" has multiple types in %s for operation: "%s" of path: "%s" in specification file: "%s".', + $propertyName, + $context['location'], + $context['method'], + $context['url'], + $context['path'] + ); + + $this->expectException(CannotParseOpenApi::class); + $this->expectExceptionMessage($exceptionMessage); + + throw CannotParseOpenApi::becauseOpenapi31TypesNotSupported($propertyName, $context); + } + public function testBecauseArrayIsNotDescribedShowsCorrectErrorMessage(): void { $propertyName = 'someRandomName';