From 8e4802b288723a85183e80ee27a485e2cfaf0f05 Mon Sep 17 00:00:00 2001 From: Djordy Koert Date: Fri, 15 Nov 2024 15:43:47 +0100 Subject: [PATCH] style: [5.x] use `@Symfony:risky` ruleset (#2397) ## Description *Please include a summary of the changes and the related issue.* Closes #... ## What type of PR is this? (check all applicable) - [ ] Bug Fix - [ ] Feature - [ ] Refactor - [ ] Deprecation - [ ] Breaking Change - [ ] Documentation Update - [ ] CI ## Checklist - [ ] I have made corresponding changes to the documentation (`docs/`) - [ ] I have made corresponding changes to the changelog (`CHANGELOG.md`) --- .php-cs-fixer.dist.php | 2 ++ src/Attribute/Areas.php | 8 ++--- src/Command/DumpCommand.php | 2 +- src/Controller/DocumentationController.php | 2 +- src/Controller/SwaggerUiController.php | 4 +-- .../YamlDocumentationController.php | 2 +- .../Compiler/TagDescribersPass.php | 2 +- src/DependencyInjection/Configuration.php | 6 ++-- .../NelmioApiDocExtension.php | 36 +++++++++---------- src/Describer/ApiPlatformDescriber.php | 4 +-- src/Describer/ExternalDocDescriber.php | 4 +-- src/Describer/OpenApiPhpDescriber.php | 6 ++-- src/Describer/RouteDescriber.php | 2 +- src/Model/ModelRegistry.php | 10 +++--- .../Annotations/ReflectionReader.php | 6 ++-- .../SymfonyConstraintAnnotationReader.php | 4 +-- .../BazingaHateoasModelDescriber.php | 2 +- src/ModelDescriber/EnumModelDescriber.php | 2 +- src/ModelDescriber/FormModelDescriber.php | 12 +++---- src/ModelDescriber/JMSModelDescriber.php | 20 +++++------ src/ModelDescriber/ObjectModelDescriber.php | 12 +++---- .../SelfDescribingModelDescriber.php | 2 +- src/OpenApiPhp/ModelRegister.php | 6 ++-- src/OpenApiPhp/Util.php | 20 +++++------ src/Processor/MapQueryStringProcessor.php | 10 +++--- src/Processor/MapRequestPayloadProcessor.php | 8 ++--- .../ArrayPropertyDescriber.php | 4 +-- .../BooleanPropertyDescriber.php | 2 +- .../CompoundPropertyDescriber.php | 2 +- .../DateTimePropertyDescriber.php | 2 +- .../DictionaryPropertyDescriber.php | 4 +-- .../FloatPropertyDescriber.php | 2 +- .../IntegerPropertyDescriber.php | 2 +- .../ObjectPropertyDescriber.php | 2 +- src/PropertyDescriber/PropertyDescriber.php | 4 +-- .../StringPropertyDescriber.php | 2 +- .../UuidPropertyDescriber.php | 2 +- src/Render/Html/GetNelmioAsset.php | 12 +++---- src/Render/Html/HtmlOpenApiRenderer.php | 2 +- src/Render/Json/JsonOpenApiRenderer.php | 4 +-- src/Render/RenderOpenApi.php | 10 +++--- src/RouteDescriber/FosRestDescriber.php | 6 ++-- src/RouteDescriber/RouteArgumentDescriber.php | 2 +- .../SymfonyMapQueryParameterDescriber.php | 28 +++++++-------- .../SymfonyMapQueryStringDescriber.php | 4 +-- .../SymfonyMapRequestPayloadDescriber.php | 4 +-- src/RouteDescriber/RouteDescriberTrait.php | 2 +- src/RouteDescriber/RouteMetadataDescriber.php | 4 +-- .../FilteredRouteCollectionBuilder.php | 12 +++---- src/Util/ControllerReflector.php | 4 +-- tests/Command/DumpCommandTest.php | 4 +-- .../MapQueryParameterController.php | 16 ++++----- tests/Functional/ControllerTest.php | 6 ++-- tests/Functional/Entity/VirtualProperty.php | 2 +- tests/Functional/TestKernel.php | 2 +- tests/Functional/WebTestCase.php | 20 +++++------ tests/Model/ModelRegistryTest.php | 4 +-- .../SymfonyConstraintAnnotationReaderTest.php | 2 +- tests/Render/RenderOpenApiTest.php | 4 +-- tests/SwaggerPhp/UtilTest.php | 36 +++++++++---------- tests/Util/ControllerReflectorTest.php | 4 +-- 61 files changed, 209 insertions(+), 207 deletions(-) diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index b8e14f420..589f90b72 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -8,8 +8,10 @@ ->exclude('tests/Functional/cache'); return (new PhpCsFixer\Config()) + ->setRiskyAllowed(true) ->setRules([ '@Symfony' => true, + '@Symfony:risky' => true, 'header_comment' => [ 'header' => <<
areas, true); + return \in_array($area, $this->areas, true); } } diff --git a/src/Command/DumpCommand.php b/src/Command/DumpCommand.php index 66dccb48b..332cc01d0 100644 --- a/src/Command/DumpCommand.php +++ b/src/Command/DumpCommand.php @@ -68,7 +68,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $options = []; if (RenderOpenApi::HTML === $format) { $rawHtmlConfig = json_decode($input->getOption('html-config'), true); - $options = is_array($rawHtmlConfig) ? $rawHtmlConfig + $this->defaultHtmlConfig : $this->defaultHtmlConfig; + $options = \is_array($rawHtmlConfig) ? $rawHtmlConfig + $this->defaultHtmlConfig : $this->defaultHtmlConfig; } elseif (RenderOpenApi::JSON === $format) { $options = [ 'no-pretty' => $input->hasParameterOption(['--no-pretty']), diff --git a/src/Controller/DocumentationController.php b/src/Controller/DocumentationController.php index da47e4ea6..cc3ab34e2 100644 --- a/src/Controller/DocumentationController.php +++ b/src/Controller/DocumentationController.php @@ -33,7 +33,7 @@ public function __invoke(Request $request, string $area = 'default'): JsonRespon $this->renderOpenApi->renderFromRequest($request, RenderOpenApi::JSON, $area) ); } catch (RenderInvalidArgumentException $e) { - throw new BadRequestHttpException(sprintf('Area "%s" is not supported as it isn\'t defined in config.', $area)); + throw new BadRequestHttpException(\sprintf('Area "%s" is not supported as it isn\'t defined in config.', $area)); } } } diff --git a/src/Controller/SwaggerUiController.php b/src/Controller/SwaggerUiController.php index 02cbfa6cc..d79d34f74 100644 --- a/src/Controller/SwaggerUiController.php +++ b/src/Controller/SwaggerUiController.php @@ -43,11 +43,11 @@ public function __invoke(Request $request, string $area = 'default'): Response return $response->setCharset('UTF-8'); } catch (RenderInvalidArgumentException $e) { $advice = ''; - if (false !== strpos($area, '.json')) { + if (str_contains($area, '.json')) { $advice = ' Since the area provided contains `.json`, the issue is likely caused by route priorities. Try switching the Swagger UI / the json documentation routes order.'; } - throw new BadRequestHttpException(sprintf('Area "%s" is not supported as it isn\'t defined in config.%s', $area, $advice), $e); + throw new BadRequestHttpException(\sprintf('Area "%s" is not supported as it isn\'t defined in config.%s', $area, $advice), $e); } } } diff --git a/src/Controller/YamlDocumentationController.php b/src/Controller/YamlDocumentationController.php index 400eab4ed..0cd65f8d4 100644 --- a/src/Controller/YamlDocumentationController.php +++ b/src/Controller/YamlDocumentationController.php @@ -36,7 +36,7 @@ public function __invoke(Request $request, string $area = 'default'): Response return $response->setCharset('UTF-8'); } catch (\InvalidArgumentException $e) { - throw new BadRequestHttpException(sprintf('Area "%s" is not supported as it isn\'t defined in config.', $area)); + throw new BadRequestHttpException(\sprintf('Area "%s" is not supported as it isn\'t defined in config.', $area)); } } } diff --git a/src/DependencyInjection/Compiler/TagDescribersPass.php b/src/DependencyInjection/Compiler/TagDescribersPass.php index 6fa54eab8..7b04ea246 100644 --- a/src/DependencyInjection/Compiler/TagDescribersPass.php +++ b/src/DependencyInjection/Compiler/TagDescribersPass.php @@ -25,7 +25,7 @@ public function process(ContainerBuilder $container): void $describer = $container->getDefinition($id); foreach ($container->getParameter('nelmio_api_doc.areas') as $area) { foreach ($tags as $tag) { - $describer->addTag(sprintf('nelmio_api_doc.describer.%s', $area), $tag); + $describer->addTag(\sprintf('nelmio_api_doc.describer.%s', $area), $tag); } } } diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index 790f24587..98296b053 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -96,7 +96,7 @@ public function getConfigTreeBuilder(): TreeBuilder ) ->beforeNormalization() ->ifTrue(function ($v) { - return 0 === count($v) || isset($v['path_patterns']) || isset($v['host_patterns']) || isset($v['documentation']); + return 0 === \count($v) || isset($v['path_patterns']) || isset($v['host_patterns']) || isset($v['documentation']); }) ->then(function ($v): array { return ['default' => $v]; @@ -171,14 +171,14 @@ public function getConfigTreeBuilder(): TreeBuilder ->variableNode('groups') ->defaultValue(null) ->validate() - ->ifTrue(function ($v) { return null !== $v && !is_array($v); }) + ->ifTrue(function ($v) { return null !== $v && !\is_array($v); }) ->thenInvalid('Model groups must be either `null` or an array.') ->end() ->end() ->variableNode('options') ->defaultValue(null) ->validate() - ->ifTrue(function ($v) { return null !== $v && !is_array($v); }) + ->ifTrue(function ($v) { return null !== $v && !\is_array($v); }) ->thenInvalid('Model options must be either `null` or an array.') ->end() ->end() diff --git a/src/DependencyInjection/NelmioApiDocExtension.php b/src/DependencyInjection/NelmioApiDocExtension.php index c699f6fa0..ca8b9fbc2 100644 --- a/src/DependencyInjection/NelmioApiDocExtension.php +++ b/src/DependencyInjection/NelmioApiDocExtension.php @@ -82,10 +82,10 @@ public function load(array $configs, ContainerBuilder $container): void foreach ($config['areas'] as $area => $areaConfig) { $areaCachePool = $areaConfig['cache']['pool'] ?? $cachePool; - $areaCacheItemId = $areaConfig['cache']['item_id'] ?? sprintf('%s.%s', $cacheItemId, $area); + $areaCacheItemId = $areaConfig['cache']['item_id'] ?? \sprintf('%s.%s', $cacheItemId, $area); $nameAliases = $this->findNameAliases($config['models']['names'], $area); - $container->register(sprintf('nelmio_api_doc.generator.%s', $area), ApiDocGenerator::class) + $container->register(\sprintf('nelmio_api_doc.generator.%s', $area), ApiDocGenerator::class) ->setPublic(true) ->addMethodCall('setAlternativeNames', [$nameAliases]) ->addMethodCall('setMediaTypes', [$config['media_types']]) @@ -93,50 +93,50 @@ public function load(array $configs, ContainerBuilder $container): void ->addMethodCall('setOpenApiVersion', [$config['documentation']['openapi'] ?? null]) ->addTag('monolog.logger', ['channel' => 'nelmio_api_doc']) ->setArguments([ - new TaggedIteratorArgument(sprintf('nelmio_api_doc.describer.%s', $area)), + new TaggedIteratorArgument(\sprintf('nelmio_api_doc.describer.%s', $area)), new TaggedIteratorArgument('nelmio_api_doc.model_describer'), null !== $areaCachePool ? new Reference($areaCachePool) : null, $areaCacheItemId, new Reference('nelmio_api_doc.open_api.generator'), ]); - $container->register(sprintf('nelmio_api_doc.describers.route.%s', $area), RouteDescriber::class) + $container->register(\sprintf('nelmio_api_doc.describers.route.%s', $area), RouteDescriber::class) ->setPublic(false) ->setArguments([ - new Reference(sprintf('nelmio_api_doc.routes.%s', $area)), + new Reference(\sprintf('nelmio_api_doc.routes.%s', $area)), new Reference('nelmio_api_doc.controller_reflector'), new TaggedIteratorArgument('nelmio_api_doc.route_describer'), ]) - ->addTag(sprintf('nelmio_api_doc.describer.%s', $area), ['priority' => -400]); + ->addTag(\sprintf('nelmio_api_doc.describer.%s', $area), ['priority' => -400]); - $container->register(sprintf('nelmio_api_doc.describers.openapi_php.%s', $area), OpenApiPhpDescriber::class) + $container->register(\sprintf('nelmio_api_doc.describers.openapi_php.%s', $area), OpenApiPhpDescriber::class) ->setPublic(false) ->setArguments([ - new Reference(sprintf('nelmio_api_doc.routes.%s', $area)), + new Reference(\sprintf('nelmio_api_doc.routes.%s', $area)), new Reference('nelmio_api_doc.controller_reflector'), new Reference('logger'), ]) - ->addTag(sprintf('nelmio_api_doc.describer.%s', $area), ['priority' => -200]); + ->addTag(\sprintf('nelmio_api_doc.describer.%s', $area), ['priority' => -200]); - $container->register(sprintf('nelmio_api_doc.describers.config.%s', $area), ExternalDocDescriber::class) + $container->register(\sprintf('nelmio_api_doc.describers.config.%s', $area), ExternalDocDescriber::class) ->setPublic(false) ->setArguments([ $areaConfig['documentation'], true, ]) - ->addTag(sprintf('nelmio_api_doc.describer.%s', $area), ['priority' => 990]); + ->addTag(\sprintf('nelmio_api_doc.describer.%s', $area), ['priority' => 990]); unset($areaConfig['documentation']); - if (0 === count($areaConfig['path_patterns']) - && 0 === count($areaConfig['host_patterns']) - && 0 === count($areaConfig['name_patterns']) + if (0 === \count($areaConfig['path_patterns']) + && 0 === \count($areaConfig['host_patterns']) + && 0 === \count($areaConfig['name_patterns']) && false === $areaConfig['with_attribute'] && false === $areaConfig['disable_default_routes'] ) { - $container->setDefinition(sprintf('nelmio_api_doc.routes.%s', $area), $routesDefinition) + $container->setDefinition(\sprintf('nelmio_api_doc.routes.%s', $area), $routesDefinition) ->setPublic(false); } else { - $container->register(sprintf('nelmio_api_doc.routes.%s', $area), RouteCollection::class) + $container->register(\sprintf('nelmio_api_doc.routes.%s', $area), RouteCollection::class) ->setPublic(false) ->setFactory([ (new Definition(FilteredRouteCollectionBuilder::class)) @@ -158,7 +158,7 @@ public function load(array $configs, ContainerBuilder $container): void ->addTag('container.service_locator') ->addArgument(array_combine( array_keys($config['areas']), - array_map(function ($area) { return new Reference(sprintf('nelmio_api_doc.generator.%s', $area)); }, array_keys($config['areas'])) + array_map(function ($area) { return new Reference(\sprintf('nelmio_api_doc.generator.%s', $area)); }, array_keys($config['areas'])) )); $container->getDefinition('nelmio_api_doc.model_describers.object') @@ -277,7 +277,7 @@ public function load(array $configs, ContainerBuilder $container): void private function findNameAliases(array $names, string $area): array { $nameAliases = array_filter($names, function (array $aliasInfo) use ($area) { - return [] === $aliasInfo['areas'] || in_array($area, $aliasInfo['areas'], true); + return [] === $aliasInfo['areas'] || \in_array($area, $aliasInfo['areas'], true); }); $aliases = []; diff --git a/src/Describer/ApiPlatformDescriber.php b/src/Describer/ApiPlatformDescriber.php index 092237ca0..7c94e8837 100644 --- a/src/Describer/ApiPlatformDescriber.php +++ b/src/Describer/ApiPlatformDescriber.php @@ -21,11 +21,11 @@ final class ApiPlatformDescriber extends ExternalDocDescriber public function __construct(object $documentation, NormalizerInterface $normalizer) { if (!$documentation instanceof DocumentationInterface && !$documentation instanceof OpenApi) { - throw new \InvalidArgumentException(sprintf('Argument 1 passed to %s() must be an instance of %s or %s. The documentation provided is an instance of %s.', __METHOD__, DocumentationInterface::class, OpenApi::class, get_class($documentation))); + throw new \InvalidArgumentException(\sprintf('Argument 1 passed to %s() must be an instance of %s or %s. The documentation provided is an instance of %s.', __METHOD__, DocumentationInterface::class, OpenApi::class, $documentation::class)); } if (!$normalizer->supportsNormalization($documentation, 'json')) { - throw new \InvalidArgumentException(sprintf('Argument 2 passed to %s() must implement %s and support normalization of %s. The normalizer provided is an instance of %s.', __METHOD__, NormalizerInterface::class, DocumentationInterface::class, get_class($normalizer))); + throw new \InvalidArgumentException(\sprintf('Argument 2 passed to %s() must implement %s and support normalization of %s. The normalizer provided is an instance of %s.', __METHOD__, NormalizerInterface::class, DocumentationInterface::class, $normalizer::class)); } parent::__construct(function () use ($documentation, $normalizer) { diff --git a/src/Describer/ExternalDocDescriber.php b/src/Describer/ExternalDocDescriber.php index 9d0d004a5..1a17093f1 100644 --- a/src/Describer/ExternalDocDescriber.php +++ b/src/Describer/ExternalDocDescriber.php @@ -46,8 +46,8 @@ public function describe(OA\OpenApi $api): void */ private function getExternalDoc(): mixed { - if (is_callable($this->externalDoc)) { - return call_user_func($this->externalDoc); + if (\is_callable($this->externalDoc)) { + return \call_user_func($this->externalDoc); } return $this->externalDoc; diff --git a/src/Describer/OpenApiPhpDescriber.php b/src/Describer/OpenApiPhpDescriber.php index 3fc5f0ef1..67ca6c5cd 100644 --- a/src/Describer/OpenApiPhpDescriber.php +++ b/src/Describer/OpenApiPhpDescriber.php @@ -59,7 +59,7 @@ public function describe(OA\OpenApi $api): void $this->setContext($context); - if (!array_key_exists($declaringClass->getName(), $classAnnotations)) { + if (!\array_key_exists($declaringClass->getName(), $classAnnotations)) { $classAnnotations[$declaringClass->getName()] = $this->getAttributesAsAnnotation($declaringClass, $context); } @@ -79,7 +79,7 @@ public function describe(OA\OpenApi $api): void } if ($annotation instanceof OA\Operation) { - if (!in_array($annotation->method, $httpMethods, true)) { + if (!\in_array($annotation->method, $httpMethods, true)) { continue; } if (Generator::UNDEFINED !== $annotation->path && $path->path !== $annotation->path) { @@ -122,7 +122,7 @@ public function describe(OA\OpenApi $api): void && !$annotation instanceof OA\Parameter && !$annotation instanceof OA\ExternalDocumentation ) { - throw new \LogicException(sprintf('Using the annotation "%s" as a root annotation in "%s::%s()" is not allowed.', get_class($annotation), $method->getDeclaringClass()->name, $method->name)); + throw new \LogicException(\sprintf('Using the annotation "%s" as a root annotation in "%s::%s()" is not allowed.', $annotation::class, $method->getDeclaringClass()->name, $method->name)); } $implicitAnnotations[] = $annotation; diff --git a/src/Describer/RouteDescriber.php b/src/Describer/RouteDescriber.php index d2a26ac65..41022e4e2 100644 --- a/src/Describer/RouteDescriber.php +++ b/src/Describer/RouteDescriber.php @@ -41,7 +41,7 @@ public function __construct(RouteCollection $routeCollection, ControllerReflecto public function describe(OA\OpenApi $api): void { - if (0 === count($this->routeDescribers)) { + if (0 === \count($this->routeDescribers)) { return; } diff --git a/src/Model/ModelRegistry.php b/src/Model/ModelRegistry.php index 544b3037e..00efab40a 100644 --- a/src/Model/ModelRegistry.php +++ b/src/Model/ModelRegistry.php @@ -102,7 +102,7 @@ public function register(Model $model): string */ public function registerSchemas(): void { - while (count($this->unregistered)) { + while (\count($this->unregistered)) { $tmp = []; foreach ($this->unregistered as $hash) { $tmp[$this->names[$hash]] = $this->models[$hash]; @@ -124,9 +124,9 @@ public function registerSchemas(): void } if (null === $schema) { - $errorMessage = sprintf('Schema of type "%s" can\'t be generated, no describer supports it.', $this->typeToString($model->getType())); + $errorMessage = \sprintf('Schema of type "%s" can\'t be generated, no describer supports it.', $this->typeToString($model->getType())); if (Type::BUILTIN_TYPE_OBJECT === $model->getType()->getBuiltinType() && !class_exists($className = $model->getType()->getClassName())) { - $errorMessage .= sprintf(' Class "\\%s" does not exist, did you forget a use statement, or typed it wrong?', $className); + $errorMessage .= \sprintf(' Class "\\%s" does not exist, did you forget a use statement, or typed it wrong?', $className); } throw new \LogicException($errorMessage); } @@ -146,13 +146,13 @@ private function generateModelName(Model $model): string { $name = $base = $this->getTypeShortName($model->getType()); $names = array_column( - $this->api->components instanceof OA\Components && is_array($this->api->components->schemas) ? $this->api->components->schemas : [], + $this->api->components instanceof OA\Components && \is_array($this->api->components->schemas) ? $this->api->components->schemas : [], 'schema' ); $i = 1; while (\in_array($name, $names, true)) { if (isset($this->registeredModelNames[$name])) { - $this->logger->info(sprintf('Can not assign a name for the model, the name "%s" has already been taken.', $name), [ + $this->logger->info(\sprintf('Can not assign a name for the model, the name "%s" has already been taken.', $name), [ 'model' => $this->modelToArray($model), 'taken_by' => $this->modelToArray($this->registeredModelNames[$name]), ]); diff --git a/src/ModelDescriber/Annotations/ReflectionReader.php b/src/ModelDescriber/Annotations/ReflectionReader.php index c83890509..7ed649ed0 100644 --- a/src/ModelDescriber/Annotations/ReflectionReader.php +++ b/src/ModelDescriber/Annotations/ReflectionReader.php @@ -46,8 +46,8 @@ public function updateProperty( $serializedName = $reflection->getName(); foreach (['get', 'is', 'has', 'can', 'add', 'remove', 'set'] as $prefix) { - if (0 === strpos($serializedName, $prefix)) { - $serializedName = substr($serializedName, strlen($prefix)); + if (str_starts_with($serializedName, $prefix)) { + $serializedName = substr($serializedName, \strlen($prefix)); } } @@ -103,7 +103,7 @@ public function setSchema(OA\Schema $schema): void */ private function getDefaultFromMethodReflection(\ReflectionMethod $reflection) { - if (0 !== strpos($reflection->name, 'set')) { + if (!str_starts_with($reflection->name, 'set')) { return Generator::UNDEFINED; } diff --git a/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php b/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php index 1861ff90a..8696a63a4 100644 --- a/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php +++ b/src/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php @@ -148,7 +148,7 @@ private function appendPattern(OA\Schema $property, ?string $newPattern): void return; } if (Generator::UNDEFINED !== $property->pattern) { - $property->pattern = sprintf('%s, %s', $property->pattern, $newPattern); + $property->pattern = \sprintf('%s, %s', $property->pattern, $newPattern); } else { $property->pattern = $newPattern; } @@ -160,7 +160,7 @@ private function appendPattern(OA\Schema $property, ?string $newPattern): void private function applyEnumFromChoiceConstraint(OA\Schema $property, Assert\Choice $choice, $reflection): void { if (null !== $choice->callback) { - $enumValues = call_user_func(is_array($choice->callback) ? $choice->callback : [$reflection->class, $choice->callback]); + $enumValues = \call_user_func(\is_array($choice->callback) ? $choice->callback : [$reflection->class, $choice->callback]); } else { $enumValues = $choice->choices; } diff --git a/src/ModelDescriber/BazingaHateoasModelDescriber.php b/src/ModelDescriber/BazingaHateoasModelDescriber.php index 10a54067e..117fe719d 100644 --- a/src/ModelDescriber/BazingaHateoasModelDescriber.php +++ b/src/ModelDescriber/BazingaHateoasModelDescriber.php @@ -105,7 +105,7 @@ private function setAttributeProperties(Relation $relation, OA\Property $subProp { foreach ($relation->getAttributes() as $attribute => $value) { $subSubProp = Util::getProperty($subProperty, $attribute); - switch (gettype($value)) { + switch (\gettype($value)) { case 'integer': $subSubProp->type = 'integer'; $subSubProp->default = $value; diff --git a/src/ModelDescriber/EnumModelDescriber.php b/src/ModelDescriber/EnumModelDescriber.php index f7b8c7781..3a4f1a569 100644 --- a/src/ModelDescriber/EnumModelDescriber.php +++ b/src/ModelDescriber/EnumModelDescriber.php @@ -40,7 +40,7 @@ public function describe(Model $model, Schema $schema): void public function supports(Model $model): bool { - if (!function_exists('enum_exists')) { + if (!\function_exists('enum_exists')) { return false; } diff --git a/src/ModelDescriber/FormModelDescriber.php b/src/ModelDescriber/FormModelDescriber.php index 6424372a3..cf89bc9e1 100644 --- a/src/ModelDescriber/FormModelDescriber.php +++ b/src/ModelDescriber/FormModelDescriber.php @@ -149,7 +149,7 @@ private function findFormType(FormConfigInterface $config, OA\Schema $property): if (null === $builtinFormType = $this->getBuiltinFormType($type)) { // if form type is not builtin in Form component. $model = new Model( - new Type(Type::BUILTIN_TYPE_OBJECT, false, get_class($type->getInnerType())), + new Type(Type::BUILTIN_TYPE_OBJECT, false, \get_class($type->getInnerType())), null, $config->getOptions() ); @@ -273,12 +273,12 @@ private function findFormType(FormConfigInterface $config, OA\Schema $property): $entityClass = $config->getOption('class'); if (true === $config->getOption('multiple')) { - $property->format = sprintf('[%s id]', $entityClass); + $property->format = \sprintf('[%s id]', $entityClass); $property->type = 'array'; $property->items = Util::createChild($property, OA\Items::class, ['type' => 'string']); } else { $property->type = 'string'; - $property->format = sprintf('%s id', $entityClass); + $property->format = \sprintf('%s id', $entityClass); } break; @@ -310,7 +310,7 @@ private function isNumbersArray(array $array): bool private function isBooleansArray(array $array): bool { foreach ($array as $item) { - if (!is_bool($item)) { + if (!\is_bool($item)) { return false; } } @@ -321,7 +321,7 @@ private function isBooleansArray(array $array): bool private function getBuiltinFormType(ResolvedFormTypeInterface $type): ?ResolvedFormTypeInterface { do { - $class = get_class($type->getInnerType()); + $class = \get_class($type->getInnerType()); if (FormType::class === $class) { return null; @@ -331,7 +331,7 @@ private function getBuiltinFormType(ResolvedFormTypeInterface $type): ?ResolvedF return $type; } - if (0 === strpos($class, 'Symfony\Component\Form\Extension\Core\Type\\')) { + if (str_starts_with($class, 'Symfony\Component\Form\Extension\Core\Type\\')) { return $type; } } while ($type = $type->getParent()); diff --git a/src/ModelDescriber/JMSModelDescriber.php b/src/ModelDescriber/JMSModelDescriber.php index 4f3e3ef54..81d376a60 100644 --- a/src/ModelDescriber/JMSModelDescriber.php +++ b/src/ModelDescriber/JMSModelDescriber.php @@ -32,8 +32,8 @@ */ class JMSModelDescriber implements ModelDescriberInterface, ModelRegistryAwareInterface { - use ModelRegistryAwareTrait; use ApplyOpenApiDiscriminatorTrait; + use ModelRegistryAwareTrait; private MetadataFactoryInterface $factory; @@ -85,7 +85,7 @@ public function describe(Model $model, OA\Schema $schema): void $className = $model->getType()->getClassName(); $metadata = $this->factory->getMetadataForClass($className); if (!$metadata instanceof ClassMetadata) { - throw new \InvalidArgumentException(sprintf('No metadata found for class %s.', $className)); + throw new \InvalidArgumentException(\sprintf('No metadata found for class %s.', $className)); } if (null !== $metadata->discriminatorFieldName @@ -133,7 +133,7 @@ public function describe(Model $model, OA\Schema $schema): void $reflections = []; if (true === $isJmsV1 && property_exists($item, 'reflection') && null !== $item->reflection) { $reflections[] = $item->reflection; - } elseif (\property_exists($item->class, $item->name)) { + } elseif (property_exists($item->class, $item->name)) { $reflections[] = new \ReflectionProperty($item->class, $item->name); } @@ -154,7 +154,7 @@ public function describe(Model $model, OA\Schema $schema): void if (true === $item->inline && isset($item->type['name'])) { // currently array types can not be documented :-/ - if (!in_array($item->type['name'], ['array', 'ArrayCollection'], true)) { + if (!\in_array($item->type['name'], ['array', 'ArrayCollection'], true)) { $inlineModel = new Model(new Type(Type::BUILTIN_TYPE_OBJECT, false, $item->type['name']), $groups); $this->describe($inlineModel, $schema); } @@ -304,11 +304,11 @@ public function describeItem(array $type, OA\Schema $property, Context $context, $property->additionalProperties = true; } elseif ('string' === $type['name']) { $property->type = 'string'; - } elseif (in_array($type['name'], ['bool', 'boolean'], true)) { + } elseif (\in_array($type['name'], ['bool', 'boolean'], true)) { $property->type = 'boolean'; - } elseif (in_array($type['name'], ['int', 'integer'], true)) { + } elseif (\in_array($type['name'], ['int', 'integer'], true)) { $property->type = 'integer'; - } elseif (in_array($type['name'], ['double', 'float'], true)) { + } elseif (\in_array($type['name'], ['double', 'float'], true)) { $property->type = 'number'; $property->format = $type['name']; } elseif (is_a($type['name'], \DateTimeInterface::class, true)) { @@ -318,13 +318,13 @@ public function describeItem(array $type, OA\Schema $property, Context $context, // See https://github.com/schmittjoh/serializer/blob/5a5a03a/src/Metadata/Driver/EnumPropertiesDriver.php#L51 if ('enum' === $type['name'] && isset($type['params'][0]) - && function_exists('enum_exists') + && \function_exists('enum_exists') ) { $typeParam = $type['params'][0]; if (isset($typeParam['name'])) { $typeParam = $typeParam['name']; } - if (is_string($typeParam) && enum_exists($typeParam)) { + if (\is_string($typeParam) && enum_exists($typeParam)) { $type['name'] = $typeParam; } @@ -385,7 +385,7 @@ private function getNestedTypeInArray(array $type): ?array */ private function propertyTypeUsesGroups(array $type): ?bool { - if (array_key_exists($type['name'], $this->propertyTypeUseGroupsCache)) { + if (\array_key_exists($type['name'], $this->propertyTypeUseGroupsCache)) { return $this->propertyTypeUseGroupsCache[$type['name']]; } diff --git a/src/ModelDescriber/ObjectModelDescriber.php b/src/ModelDescriber/ObjectModelDescriber.php index 3e950204c..7e32dd8fb 100644 --- a/src/ModelDescriber/ObjectModelDescriber.php +++ b/src/ModelDescriber/ObjectModelDescriber.php @@ -27,8 +27,8 @@ class ObjectModelDescriber implements ModelDescriberInterface, ModelRegistryAwareInterface { - use ModelRegistryAwareTrait; use ApplyOpenApiDiscriminatorTrait; + use ModelRegistryAwareTrait; private PropertyInfoExtractorInterface $propertyInfo; private ?ClassMetadataFactoryInterface $classMetadataFactory; @@ -124,7 +124,7 @@ public function describe(Model $model, OA\Schema $schema): void // Interpret additional options $groups = $model->getGroups(); - if (isset($groups[$propertyName]) && is_array($groups[$propertyName])) { + if (isset($groups[$propertyName]) && \is_array($groups[$propertyName])) { $groups = $model->getGroups()[$propertyName]; } foreach ($reflections as $reflection) { @@ -137,8 +137,8 @@ public function describe(Model $model, OA\Schema $schema): void } $types = $this->propertyInfo->getTypes($class, $propertyName); - if (null === $types || 0 === count($types)) { - throw new \LogicException(sprintf('The PropertyInfo component was not able to guess the type of %s::$%s. You may need to add a `@var` annotation or use `#[OA\Property(type="")]` to make its type explicit.', $class, $propertyName)); + if (null === $types || 0 === \count($types)) { + throw new \LogicException(\sprintf('The PropertyInfo component was not able to guess the type of %s::$%s. You may need to add a `@var` annotation or use `#[OA\Property(type="")]` to make its type explicit.', $class, $propertyName)); } $this->describeProperty($types, $model, $property, $propertyName); @@ -189,7 +189,7 @@ private function describeProperty(array $types, Model $model, OA\Schema $propert return; } - throw new \Exception(sprintf('Type "%s" is not supported in %s::$%s. You may use the `#[OA\Property(type="")]` annotation to specify it manually.', $types[0]->getBuiltinType(), $model->getType()->getClassName(), $propertyName)); + throw new \Exception(\sprintf('Type "%s" is not supported in %s::$%s. You may use the `#[OA\Property(type="")]` annotation to specify it manually.', $types[0]->getBuiltinType(), $model->getType()->getClassName(), $propertyName)); } /** @@ -204,7 +204,7 @@ private function markRequiredProperties(OA\Schema $schema): void $newRequired = []; foreach ($properties as $property) { - if (is_array($schema->required) && \in_array($property->property, $schema->required, true)) { + if (\is_array($schema->required) && \in_array($property->property, $schema->required, true)) { $newRequired[] = $property->property; continue; } diff --git a/src/ModelDescriber/SelfDescribingModelDescriber.php b/src/ModelDescriber/SelfDescribingModelDescriber.php index fce60ea37..8d34a55e7 100644 --- a/src/ModelDescriber/SelfDescribingModelDescriber.php +++ b/src/ModelDescriber/SelfDescribingModelDescriber.php @@ -18,7 +18,7 @@ class SelfDescribingModelDescriber implements ModelDescriberInterface { public function describe(Model $model, OA\Schema $schema): void { - call_user_func([$model->getType()->getClassName(), 'describe'], $schema, $model); + \call_user_func([$model->getType()->getClassName(), 'describe'], $schema, $model); } public function supports(Model $model): bool diff --git a/src/OpenApiPhp/ModelRegister.php b/src/OpenApiPhp/ModelRegister.php index a33fcd4d9..fb2776d01 100644 --- a/src/OpenApiPhp/ModelRegister.php +++ b/src/OpenApiPhp/ModelRegister.php @@ -60,7 +60,7 @@ public function __invoke(Analysis $analysis, ?array $parentGroups = null): void // Misusage of ::$ref if (($annotation instanceof OA\Response || $annotation instanceof OA\RequestBody) && $annotation->ref instanceof ModelAnnotation) { - throw new \InvalidArgumentException(sprintf('Using #[Model] inside #[%s::$ref] is not allowed. You should use ::$ref with #[Property], #[Parameter], #[Schema], #[Items] but within #[Response] or #[RequestBody} You should use ::$content : `#[Response(..., content: new Model())]`.', get_class($annotation))); + throw new \InvalidArgumentException(\sprintf('Using #[Model] inside #[%s::$ref] is not allowed. You should use ::$ref with #[Property], #[Parameter], #[Schema], #[Items] but within #[Response] or #[RequestBody} You should use ::$content : `#[Response(..., content: new Model())]`.', $annotation::class)); } // Implicit usages @@ -88,7 +88,7 @@ public function __invoke(Analysis $analysis, ?array $parentGroups = null): void } if (!$annotation instanceof OA\Parameter) { - throw new \InvalidArgumentException(sprintf("#[Model] attribute can't be nested with an attribute of type @%s.", get_class($annotation))); + throw new \InvalidArgumentException(\sprintf("#[Model] attribute can't be nested with an attribute of type @%s.", $annotation::class)); } if ($annotation->schema instanceof OA\Schema && 'array' === $annotation->schema->type) { @@ -176,7 +176,7 @@ private function createContentForMediaType( break; default: - throw new \InvalidArgumentException(sprintf("#[Model] attribute is not compatible with the media types '%s'. It must be one of 'json' or 'xml'.", implode(',', $this->mediaTypes))); + throw new \InvalidArgumentException(\sprintf("#[Model] attribute is not compatible with the media types '%s'. It must be one of 'json' or 'xml'.", implode(',', $this->mediaTypes))); } $annotation->merge([$modelAnnotation]); diff --git a/src/OpenApiPhp/Util.php b/src/OpenApiPhp/Util.php index 960374846..1444b4d26 100644 --- a/src/OpenApiPhp/Util.php +++ b/src/OpenApiPhp/Util.php @@ -82,7 +82,7 @@ public static function getTag(OA\OpenApi $api, string $name): OA\Tag // Tags ar not considered indexed, so we cannot use getIndexedCollectionItem directly // because we need to specify that the search should use the "name" property. $key = self::searchIndexedCollectionItem( - is_array($api->tags) ? $api->tags : [], + \is_array($api->tags) ? $api->tags : [], 'name', $name ); @@ -139,7 +139,7 @@ public static function getProperty(OA\Schema $schema, string $property): OA\Prop */ public static function getOperation(OA\PathItem $path, string $method): OA\Operation { - $class = array_keys($path::$_nested, \strtolower($method), true)[0]; + $class = array_keys($path::$_nested, strtolower($method), true)[0]; if (!is_a($class, OA\Operation::class, true)) { throw new \InvalidArgumentException('Invalid operation class provided.'); @@ -417,10 +417,10 @@ public static function merge(OA\AbstractAnnotation $annotation, $from, bool $ove { if (\is_array($from)) { self::mergeFromArray($annotation, $from, $overwrite); - } elseif (\is_a($from, OA\AbstractAnnotation::class)) { + } elseif (is_a($from, OA\AbstractAnnotation::class)) { /* @var OA\AbstractAnnotation $from */ self::mergeFromArray($annotation, json_decode(json_encode($from), true), $overwrite); - } elseif (\is_a($from, \ArrayObject::class)) { + } elseif (is_a($from, \ArrayObject::class)) { /* @var \ArrayObject $from */ self::mergeFromArray($annotation, $from->getArrayCopy(), $overwrite); } @@ -451,12 +451,12 @@ private static function mergeFromArray(OA\AbstractAnnotation $annotation, array { $done = []; - $defaults = \get_class_vars(\get_class($annotation)); + $defaults = get_class_vars($annotation::class); foreach ($annotation::$_nested as $className => $propertyName) { if (\is_string($propertyName)) { - if (array_key_exists($propertyName, $properties)) { - if (!is_bool($properties[$propertyName])) { + if (\array_key_exists($propertyName, $properties)) { + if (!\is_bool($properties[$propertyName])) { self::mergeChild($annotation, $className, $properties[$propertyName], $overwrite); } elseif ($overwrite || $annotation->{$propertyName} === $defaults[$propertyName]) { // Support for boolean values (for instance for additionalProperties) @@ -473,7 +473,7 @@ private static function mergeFromArray(OA\AbstractAnnotation $annotation, array } foreach ($annotation::$_types as $propertyName => $type) { - if (array_key_exists($propertyName, $properties)) { + if (\array_key_exists($propertyName, $properties)) { self::mergeTyped($annotation, $propertyName, $type, $properties, $defaults, $overwrite); $done[] = $propertyName; } @@ -496,7 +496,7 @@ private static function mergeFromArray(OA\AbstractAnnotation $annotation, array $propertyName = 'ref'; } - if (array_key_exists($propertyName, $defaults) && !\in_array($propertyName, $done, true)) { + if (\array_key_exists($propertyName, $defaults) && !\in_array($propertyName, $done, true)) { self::mergeProperty($annotation, $propertyName, $value, $defaults[$propertyName], $overwrite); } } @@ -550,7 +550,7 @@ private static function mergeCollection(OA\AbstractAnnotation $annotation, strin */ private static function mergeTyped(OA\AbstractAnnotation $annotation, string $propertyName, $type, array $properties, array $defaults, bool $overwrite): void { - if (\is_string($type) && 0 === strpos($type, '[')) { + if (\is_string($type) && str_starts_with($type, '[')) { $innerType = substr($type, 1, -1); if (!$annotation->{$propertyName} || Generator::UNDEFINED === $annotation->{$propertyName}) { diff --git a/src/Processor/MapQueryStringProcessor.php b/src/Processor/MapQueryStringProcessor.php index 79223aa93..943748e1e 100644 --- a/src/Processor/MapQueryStringProcessor.php +++ b/src/Processor/MapQueryStringProcessor.php @@ -39,8 +39,8 @@ public function __invoke(Analysis $analysis): void } $mapQueryStringContexts = $operation->_context->{SymfonyMapQueryStringDescriber::CONTEXT_KEY}; - if (!is_array($mapQueryStringContexts)) { - throw new \LogicException(sprintf('MapQueryString contexts not found for operation "%s"', $operation->operationId)); + if (!\is_array($mapQueryStringContexts)) { + throw new \LogicException(\sprintf('MapQueryString contexts not found for operation "%s"', $operation->operationId)); } foreach ($mapQueryStringContexts as $mapQueryStringContext) { @@ -56,12 +56,12 @@ private function addQueryParameters(Analysis $analysis, OA\Operation $operation, { $argumentMetaData = $mapQueryStringContext[SymfonyMapQueryStringDescriber::CONTEXT_ARGUMENT_METADATA]; if (!$argumentMetaData instanceof ArgumentMetadata) { - throw new \LogicException(sprintf('MapQueryString ArgumentMetaData not found for operation "%s"', $operation->operationId)); + throw new \LogicException(\sprintf('MapQueryString ArgumentMetaData not found for operation "%s"', $operation->operationId)); } $modelRef = $mapQueryStringContext[SymfonyMapQueryStringDescriber::CONTEXT_MODEL_REF]; if (!isset($modelRef)) { - throw new \LogicException(sprintf('MapQueryString Model reference not found for operation "%s"', $operation->operationId)); + throw new \LogicException(\sprintf('MapQueryString Model reference not found for operation "%s"', $operation->operationId)); } $nativeModelName = str_replace(OA\Components::SCHEMA_REF, '', $modelRef); @@ -97,7 +97,7 @@ private function addQueryParameters(Analysis $analysis, OA\Operation $operation, if ($isModelOptional) { Util::modifyAnnotationValue($operationParameter, 'required', false); - } elseif (is_array($schemaModel->required) && in_array($property->property, $schemaModel->required, true)) { + } elseif (\is_array($schemaModel->required) && \in_array($property->property, $schemaModel->required, true)) { Util::modifyAnnotationValue($operationParameter, 'required', true); } else { Util::modifyAnnotationValue($operationParameter, 'required', false); diff --git a/src/Processor/MapRequestPayloadProcessor.php b/src/Processor/MapRequestPayloadProcessor.php index 351baf393..95a6eea27 100644 --- a/src/Processor/MapRequestPayloadProcessor.php +++ b/src/Processor/MapRequestPayloadProcessor.php @@ -41,16 +41,16 @@ public function __invoke(Analysis $analysis): void $argumentMetaData = $operation->_context->{SymfonyMapRequestPayloadDescriber::CONTEXT_ARGUMENT_METADATA}; if (!$argumentMetaData instanceof ArgumentMetadata) { - throw new \LogicException(sprintf('MapRequestPayload ArgumentMetaData not found for operation "%s"', $operation->operationId)); + throw new \LogicException(\sprintf('MapRequestPayload ArgumentMetaData not found for operation "%s"', $operation->operationId)); } /** @var MapRequestPayload $attribute */ if (!$attribute = $argumentMetaData->getAttributes(MapRequestPayload::class, ArgumentMetadata::IS_INSTANCEOF)[0] ?? null) { - throw new \LogicException(sprintf('Operation "%s" does not contain attribute of "%s', $operation->operationId, MapRequestPayload::class)); + throw new \LogicException(\sprintf('Operation "%s" does not contain attribute of "%s', $operation->operationId, MapRequestPayload::class)); } if (!isset($operation->_context->{SymfonyMapRequestPayloadDescriber::CONTEXT_MODEL_REF})) { - throw new \LogicException(sprintf('MapRequestPayload Model reference not found for operation "%s"', $operation->operationId)); + throw new \LogicException(\sprintf('MapRequestPayload Model reference not found for operation "%s"', $operation->operationId)); } $modelRef = $operation->_context->{SymfonyMapRequestPayloadDescriber::CONTEXT_MODEL_REF}; @@ -59,7 +59,7 @@ public function __invoke(Analysis $analysis): void Util::modifyAnnotationValue($requestBody, 'required', !($argumentMetaData->hasDefaultValue() || $argumentMetaData->isNullable())); $formats = $attribute->acceptFormat; - if (!is_array($formats)) { + if (!\is_array($formats)) { $formats = [$attribute->acceptFormat ?? 'json']; } diff --git a/src/PropertyDescriber/ArrayPropertyDescriber.php b/src/PropertyDescriber/ArrayPropertyDescriber.php index ae853b66f..2d6e997bc 100644 --- a/src/PropertyDescriber/ArrayPropertyDescriber.php +++ b/src/PropertyDescriber/ArrayPropertyDescriber.php @@ -44,7 +44,7 @@ public function describe(array $types, OA\Schema $property, array $context = []) public function supports(array $types, array $context = []): bool { - if (1 !== count($types) || !$types[0]->isCollection()) { + if (1 !== \count($types) || !$types[0]->isCollection()) { return false; } @@ -52,7 +52,7 @@ public function supports(array $types, array $context = []): bool return true; } - return 1 === count($types[0]->getCollectionKeyTypes()) + return 1 === \count($types[0]->getCollectionKeyTypes()) && Type::BUILTIN_TYPE_INT === $types[0]->getCollectionKeyTypes()[0]->getBuiltinType(); } } diff --git a/src/PropertyDescriber/BooleanPropertyDescriber.php b/src/PropertyDescriber/BooleanPropertyDescriber.php index 1f6ee0daa..0a8fc968f 100644 --- a/src/PropertyDescriber/BooleanPropertyDescriber.php +++ b/src/PropertyDescriber/BooleanPropertyDescriber.php @@ -26,6 +26,6 @@ public function describe(array $types, OA\Schema $property, array $context = []) public function supports(array $types, array $context = []): bool { - return 1 === count($types) && Type::BUILTIN_TYPE_BOOL === $types[0]->getBuiltinType(); + return 1 === \count($types) && Type::BUILTIN_TYPE_BOOL === $types[0]->getBuiltinType(); } } diff --git a/src/PropertyDescriber/CompoundPropertyDescriber.php b/src/PropertyDescriber/CompoundPropertyDescriber.php index b538c2f95..29ff6304e 100644 --- a/src/PropertyDescriber/CompoundPropertyDescriber.php +++ b/src/PropertyDescriber/CompoundPropertyDescriber.php @@ -38,6 +38,6 @@ public function describe(array $types, OA\Schema $property, array $context = []) public function supports(array $types, array $context = []): bool { - return count($types) >= 2; + return \count($types) >= 2; } } diff --git a/src/PropertyDescriber/DateTimePropertyDescriber.php b/src/PropertyDescriber/DateTimePropertyDescriber.php index 81c063ed0..f605a2961 100644 --- a/src/PropertyDescriber/DateTimePropertyDescriber.php +++ b/src/PropertyDescriber/DateTimePropertyDescriber.php @@ -27,7 +27,7 @@ public function describe(array $types, OA\Schema $property, array $context = []) public function supports(array $types, array $context = []): bool { - return 1 === count($types) + return 1 === \count($types) && Type::BUILTIN_TYPE_OBJECT === $types[0]->getBuiltinType() && is_a($types[0]->getClassName(), \DateTimeInterface::class, true); } diff --git a/src/PropertyDescriber/DictionaryPropertyDescriber.php b/src/PropertyDescriber/DictionaryPropertyDescriber.php index 454469c6f..2e6575fde 100644 --- a/src/PropertyDescriber/DictionaryPropertyDescriber.php +++ b/src/PropertyDescriber/DictionaryPropertyDescriber.php @@ -36,9 +36,9 @@ public function describe(array $types, OA\Schema $property, array $context = []) public function supports(array $types, array $context = []): bool { - return 1 === count($types) + return 1 === \count($types) && $types[0]->isCollection() - && 1 === count($types[0]->getCollectionKeyTypes()) + && 1 === \count($types[0]->getCollectionKeyTypes()) && Type::BUILTIN_TYPE_STRING === $types[0]->getCollectionKeyTypes()[0]->getBuiltinType(); } } diff --git a/src/PropertyDescriber/FloatPropertyDescriber.php b/src/PropertyDescriber/FloatPropertyDescriber.php index ad08aeaa0..a37de109c 100644 --- a/src/PropertyDescriber/FloatPropertyDescriber.php +++ b/src/PropertyDescriber/FloatPropertyDescriber.php @@ -27,6 +27,6 @@ public function describe(array $types, OA\Schema $property, array $context = []) public function supports(array $types, array $context = []): bool { - return 1 === count($types) && Type::BUILTIN_TYPE_FLOAT === $types[0]->getBuiltinType(); + return 1 === \count($types) && Type::BUILTIN_TYPE_FLOAT === $types[0]->getBuiltinType(); } } diff --git a/src/PropertyDescriber/IntegerPropertyDescriber.php b/src/PropertyDescriber/IntegerPropertyDescriber.php index cd1a5b03f..a949aa2c9 100644 --- a/src/PropertyDescriber/IntegerPropertyDescriber.php +++ b/src/PropertyDescriber/IntegerPropertyDescriber.php @@ -26,6 +26,6 @@ public function describe(array $types, OA\Schema $property, array $context = []) public function supports(array $types, array $context = []): bool { - return 1 === count($types) && Type::BUILTIN_TYPE_INT === $types[0]->getBuiltinType(); + return 1 === \count($types) && Type::BUILTIN_TYPE_INT === $types[0]->getBuiltinType(); } } diff --git a/src/PropertyDescriber/ObjectPropertyDescriber.php b/src/PropertyDescriber/ObjectPropertyDescriber.php index 5ece1385e..c7563b6d3 100644 --- a/src/PropertyDescriber/ObjectPropertyDescriber.php +++ b/src/PropertyDescriber/ObjectPropertyDescriber.php @@ -49,7 +49,7 @@ public function describe(array $types, OA\Schema $property, array $context = []) public function supports(array $types, array $context = []): bool { - return 1 === count($types) + return 1 === \count($types) && Type::BUILTIN_TYPE_OBJECT === $types[0]->getBuiltinType(); } } diff --git a/src/PropertyDescriber/PropertyDescriber.php b/src/PropertyDescriber/PropertyDescriber.php index 100f1788c..03793ae1b 100644 --- a/src/PropertyDescriber/PropertyDescriber.php +++ b/src/PropertyDescriber/PropertyDescriber.php @@ -77,8 +77,8 @@ private function getPropertyDescriber(array $types, array $context): ?PropertyDe } // Prevent infinite recursion - if (key_exists($this->getHash($types), $this->called)) { - if (in_array($propertyDescriber, $this->called[$this->getHash($types)], true)) { + if (\array_key_exists($this->getHash($types), $this->called)) { + if (\in_array($propertyDescriber, $this->called[$this->getHash($types)], true)) { continue; } } diff --git a/src/PropertyDescriber/StringPropertyDescriber.php b/src/PropertyDescriber/StringPropertyDescriber.php index ea82f0f9d..cfc00c24f 100644 --- a/src/PropertyDescriber/StringPropertyDescriber.php +++ b/src/PropertyDescriber/StringPropertyDescriber.php @@ -26,6 +26,6 @@ public function describe(array $types, OA\Schema $property, array $context = []) public function supports(array $types, array $context = []): bool { - return 1 === count($types) && Type::BUILTIN_TYPE_STRING === $types[0]->getBuiltinType(); + return 1 === \count($types) && Type::BUILTIN_TYPE_STRING === $types[0]->getBuiltinType(); } } diff --git a/src/PropertyDescriber/UuidPropertyDescriber.php b/src/PropertyDescriber/UuidPropertyDescriber.php index f8294be95..7151eebdb 100644 --- a/src/PropertyDescriber/UuidPropertyDescriber.php +++ b/src/PropertyDescriber/UuidPropertyDescriber.php @@ -28,7 +28,7 @@ public function describe(array $types, OA\Schema $property, array $context = []) public function supports(array $types, array $context = []): bool { - return 1 === count($types) + return 1 === \count($types) && Type::BUILTIN_TYPE_OBJECT === $types[0]->getBuiltinType() && is_a($types[0]->getClassName(), AbstractUid::class, true); } diff --git a/src/Render/Html/GetNelmioAsset.php b/src/Render/Html/GetNelmioAsset.php index bb15af4e8..821ba04a5 100644 --- a/src/Render/Html/GetNelmioAsset.php +++ b/src/Render/Html/GetNelmioAsset.php @@ -71,32 +71,32 @@ private function getExtension(string $assetsMode, string $asset): array */ private function getResource(string $asset, string $mode): array { - if (filter_var($asset, FILTER_VALIDATE_URL)) { + if (filter_var($asset, \FILTER_VALIDATE_URL)) { return [$asset, false]; } elseif (AssetsMode::OFFLINE === $mode) { return [file_get_contents($this->resourcesDir.'/'.$asset), true]; } elseif (AssetsMode::CDN === $mode) { return [$this->cdnUrl.'/'.$asset, false]; } else { - return [$this->assetExtension->getAssetUrl(sprintf('bundles/nelmioapidoc/%s', $asset)), false]; + return [$this->assetExtension->getAssetUrl(\sprintf('bundles/nelmioapidoc/%s', $asset)), false]; } } private function renderJavascript(string $script, bool $isInline): string { if ($isInline) { - return sprintf('', $script); + return \sprintf('', $script); } else { - return sprintf('', $script); + return \sprintf('', $script); } } private function renderCss(string $stylesheet, bool $isInline): string { if ($isInline) { - return sprintf('', $stylesheet); + return \sprintf('', $stylesheet); } else { - return sprintf('', $stylesheet); + return \sprintf('', $stylesheet); } } } diff --git a/src/Render/Html/HtmlOpenApiRenderer.php b/src/Render/Html/HtmlOpenApiRenderer.php index 4794e4abe..bb6a3f42a 100644 --- a/src/Render/Html/HtmlOpenApiRenderer.php +++ b/src/Render/Html/HtmlOpenApiRenderer.php @@ -33,7 +33,7 @@ class HtmlOpenApiRenderer implements OpenApiRenderer public function __construct($twig, array $htmlConfig) { if (!$twig instanceof \Twig_Environment && !$twig instanceof Environment) { - throw new \InvalidArgumentException(sprintf('Providing an instance of "%s" as twig is not supported.', get_class($twig))); + throw new \InvalidArgumentException(\sprintf('Providing an instance of "%s" as twig is not supported.', $twig::class)); } $this->twig = $twig; $this->htmlConfig = $htmlConfig; diff --git a/src/Render/Json/JsonOpenApiRenderer.php b/src/Render/Json/JsonOpenApiRenderer.php index b903f72ae..ff8008c41 100644 --- a/src/Render/Json/JsonOpenApiRenderer.php +++ b/src/Render/Json/JsonOpenApiRenderer.php @@ -30,8 +30,8 @@ public function render(OpenApi $spec, array $options = []): string $options += [ 'no-pretty' => false, ]; - $flags = true === $options['no-pretty'] ? 0 : JSON_PRETTY_PRINT; + $flags = true === $options['no-pretty'] ? 0 : \JSON_PRETTY_PRINT; - return json_encode($spec, $flags | JSON_UNESCAPED_SLASHES); + return json_encode($spec, $flags | \JSON_UNESCAPED_SLASHES); } } diff --git a/src/Render/RenderOpenApi.php b/src/Render/RenderOpenApi.php index a7d1ae5c5..6a32a1309 100644 --- a/src/Render/RenderOpenApi.php +++ b/src/Render/RenderOpenApi.php @@ -76,9 +76,9 @@ public function renderFromRequest(Request $request, string $format, string $area public function render(string $format, string $area, array $options = []): string { if (!$this->generatorLocator->has($area)) { - throw new RenderInvalidArgumentException(sprintf('Area "%s" is not supported.', $area)); - } elseif (!array_key_exists($format, $this->openApiRenderers)) { - throw new RenderInvalidArgumentException(sprintf('Format "%s" is not supported.', $format)); + throw new RenderInvalidArgumentException(\sprintf('Area "%s" is not supported.', $area)); + } elseif (!\array_key_exists($format, $this->openApiRenderers)) { + throw new RenderInvalidArgumentException(\sprintf('Format "%s" is not supported.', $format)); } /** @var OpenApi $spec */ @@ -100,7 +100,7 @@ public function render(string $format, string $area, array $options = []): strin */ private function getServersFromOptions(OpenApi $spec, array $options) { - if (array_key_exists('server_url', $options)) { + if (\array_key_exists('server_url', $options)) { return [new Server(['url' => $options['server_url'], '_context' => new Context()])]; } @@ -108,7 +108,7 @@ private function getServersFromOptions(OpenApi $spec, array $options) return $spec->servers; } - if (array_key_exists('fallback_url', $options)) { + if (\array_key_exists('fallback_url', $options)) { return [new Server(['url' => $options['fallback_url'], '_context' => new Context()])]; } diff --git a/src/RouteDescriber/FosRestDescriber.php b/src/RouteDescriber/FosRestDescriber.php index ee7ddbcd6..b8ccb244a 100644 --- a/src/RouteDescriber/FosRestDescriber.php +++ b/src/RouteDescriber/FosRestDescriber.php @@ -72,7 +72,7 @@ public function describe(OA\OpenApi $api, Route $route, \ReflectionMethod $refle $schema = Util::getProperty($contentSchema, $parameterName); if (!$attribute->nullable && $attribute->strict) { - $requiredParameters = is_array($contentSchema->required) ? $contentSchema->required : []; + $requiredParameters = \is_array($contentSchema->required) ? $contentSchema->required : []; $requiredParameters[] = $parameterName; $contentSchema->required = array_values(array_unique($requiredParameters)); @@ -89,11 +89,11 @@ public function describe(OA\OpenApi $api, Route $route, \ReflectionMethod $refle */ private function getPattern($requirements): ?string { - if (is_array($requirements) && isset($requirements['rule'])) { + if (\is_array($requirements) && isset($requirements['rule'])) { return (string) $requirements['rule']; } - if (is_string($requirements)) { + if (\is_string($requirements)) { return $requirements; } diff --git a/src/RouteDescriber/RouteArgumentDescriber.php b/src/RouteDescriber/RouteArgumentDescriber.php index b79699bdc..c5a9379ba 100644 --- a/src/RouteDescriber/RouteArgumentDescriber.php +++ b/src/RouteDescriber/RouteArgumentDescriber.php @@ -22,8 +22,8 @@ final class RouteArgumentDescriber implements RouteDescriberInterface, ModelRegistryAwareInterface { - use RouteDescriberTrait; use ModelRegistryAwareTrait; + use RouteDescriberTrait; /** * @param RouteArgumentDescriberInterface[] $inlineParameterDescribers diff --git a/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapQueryParameterDescriber.php b/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapQueryParameterDescriber.php index 6cc5ea9f8..26bf2a807 100644 --- a/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapQueryParameterDescriber.php +++ b/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapQueryParameterDescriber.php @@ -84,58 +84,58 @@ private function describeValidateFilter(?int $filter, int $flags, array $options return []; } - if (FILTER_VALIDATE_BOOLEAN === $filter) { + if (\FILTER_VALIDATE_BOOLEAN === $filter) { return ['type' => 'boolean']; } - if (FILTER_VALIDATE_DOMAIN === $filter) { + if (\FILTER_VALIDATE_DOMAIN === $filter) { return ['type' => 'string', 'format' => 'hostname']; } - if (FILTER_VALIDATE_EMAIL === $filter) { + if (\FILTER_VALIDATE_EMAIL === $filter) { return ['type' => 'string', 'format' => 'email']; } - if (FILTER_VALIDATE_FLOAT === $filter) { + if (\FILTER_VALIDATE_FLOAT === $filter) { return ['type' => 'number', 'format' => 'float']; } - if (FILTER_VALIDATE_INT === $filter) { + if (\FILTER_VALIDATE_INT === $filter) { $props = []; - if (array_key_exists('min_range', $options)) { + if (\array_key_exists('min_range', $options)) { $props['minimum'] = $options['min_range']; } - if (array_key_exists('max_range', $options)) { + if (\array_key_exists('max_range', $options)) { $props['maximum'] = $options['max_range']; } return ['type' => 'integer', ...$props]; } - if (FILTER_VALIDATE_IP === $filter) { + if (\FILTER_VALIDATE_IP === $filter) { $format = match ($flags) { - FILTER_FLAG_IPV4 => 'ipv4', - FILTER_FLAG_IPV6 => 'ipv6', + \FILTER_FLAG_IPV4 => 'ipv4', + \FILTER_FLAG_IPV6 => 'ipv6', default => 'ip', }; return ['type' => 'string', 'format' => $format]; } - if (FILTER_VALIDATE_MAC === $filter) { + if (\FILTER_VALIDATE_MAC === $filter) { return ['type' => 'string', 'format' => 'mac']; } - if (FILTER_VALIDATE_REGEXP === $filter) { + if (\FILTER_VALIDATE_REGEXP === $filter) { return ['type' => 'string', 'pattern' => $options['regexp']]; } - if (FILTER_VALIDATE_URL === $filter) { + if (\FILTER_VALIDATE_URL === $filter) { return ['type' => 'string', 'format' => 'uri']; } - if (FILTER_DEFAULT === $filter) { + if (\FILTER_DEFAULT === $filter) { return ['type' => 'string']; } diff --git a/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapQueryStringDescriber.php b/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapQueryStringDescriber.php index 32e1956be..64eb2b1d9 100644 --- a/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapQueryStringDescriber.php +++ b/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapQueryStringDescriber.php @@ -59,11 +59,11 @@ public function describe(ArgumentMetadata $argumentMetadata, OA\Operation $opera */ private function getGroups(MapQueryString $attribute): ?array { - if (is_string($attribute->validationGroups)) { + if (\is_string($attribute->validationGroups)) { return [$attribute->validationGroups]; } - if (is_array($attribute->validationGroups)) { + if (\is_array($attribute->validationGroups)) { return $attribute->validationGroups; } diff --git a/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapRequestPayloadDescriber.php b/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapRequestPayloadDescriber.php index 4e5115ec6..ffbbe9a59 100644 --- a/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapRequestPayloadDescriber.php +++ b/src/RouteDescriber/RouteArgumentDescriber/SymfonyMapRequestPayloadDescriber.php @@ -57,11 +57,11 @@ public function describe(ArgumentMetadata $argumentMetadata, OA\Operation $opera */ private function getGroups(MapRequestPayload $attribute): ?array { - if (is_string($attribute->validationGroups)) { + if (\is_string($attribute->validationGroups)) { return [$attribute->validationGroups]; } - if (is_array($attribute->validationGroups)) { + if (\is_array($attribute->validationGroups)) { return $attribute->validationGroups; } diff --git a/src/RouteDescriber/RouteDescriberTrait.php b/src/RouteDescriber/RouteDescriberTrait.php index 66c9b35bb..9efb1677e 100644 --- a/src/RouteDescriber/RouteDescriberTrait.php +++ b/src/RouteDescriber/RouteDescriberTrait.php @@ -36,7 +36,7 @@ private function getOperations(OpenApi $api, Route $route): array foreach ($methods as $method) { $method = strtolower($method); - if (!in_array($method, Util::OPERATIONS, true)) { + if (!\in_array($method, Util::OPERATIONS, true)) { continue; } diff --git a/src/RouteDescriber/RouteMetadataDescriber.php b/src/RouteDescriber/RouteMetadataDescriber.php index b881bead7..68b7edf21 100644 --- a/src/RouteDescriber/RouteMetadataDescriber.php +++ b/src/RouteDescriber/RouteMetadataDescriber.php @@ -95,7 +95,7 @@ private function getRefParams(OA\OpenApi $api, OA\Operation $operation): array continue; } - $ref = \mb_substr($ref, 24); // trim the '#/components/parameters/' part of ref + $ref = mb_substr($ref, 24); // trim the '#/components/parameters/' part of ref if (!isset($globalParams[$ref])) { // this shouldn't happen during proper configs, but in case of bad config, just ignore it here continue; @@ -121,7 +121,7 @@ private function getRefParams(OA\OpenApi $api, OA\Operation $operation): array private function getPossibleEnumValues(string $reqPattern): array { $requirements = []; - if (false !== strpos($reqPattern, '|')) { + if (str_contains($reqPattern, '|')) { $parts = explode('|', $reqPattern); foreach ($parts as $part) { if ('' === $part || 0 === preg_match(self::ALPHANUM_EXPANDED_REGEX, $part)) { diff --git a/src/Routing/FilteredRouteCollectionBuilder.php b/src/Routing/FilteredRouteCollectionBuilder.php index 319b87e03..88bf0eff4 100644 --- a/src/Routing/FilteredRouteCollectionBuilder.php +++ b/src/Routing/FilteredRouteCollectionBuilder.php @@ -83,7 +83,7 @@ private function matchPath(Route $route): bool } } - return 0 === count($this->options['path_patterns']); + return 0 === \count($this->options['path_patterns']); } private function matchHost(Route $route): bool @@ -94,7 +94,7 @@ private function matchHost(Route $route): bool } } - return 0 === count($this->options['host_patterns']); + return 0 === \count($this->options['host_patterns']); } private function matchName(string $name): bool @@ -105,7 +105,7 @@ private function matchName(string $name): bool } } - return 0 === count($this->options['name_patterns']); + return 0 === \count($this->options['name_patterns']); } private function matchAnnotation(Route $route): bool @@ -146,9 +146,9 @@ private function defaultRouteDisabled(Route $route): bool }, $method->getAttributes(AbstractAnnotation::class, \ReflectionAttribute::IS_INSTANCEOF)); foreach ($annotations as $annotation) { - if (false !== strpos(get_class($annotation), 'Nelmio\\ApiDocBundle\\Attribute') - || false !== strpos(get_class($annotation), 'OpenApi\\Annotations') - || false !== strpos(get_class($annotation), 'OpenApi\\Attributes') + if (str_contains($annotation::class, 'Nelmio\\ApiDocBundle\\Attribute') + || str_contains($annotation::class, 'OpenApi\\Annotations') + || str_contains($annotation::class, 'OpenApi\\Attributes') ) { return true; } diff --git a/src/Util/ControllerReflector.php b/src/Util/ControllerReflector.php index c986bcfdf..43ad14458 100644 --- a/src/Util/ControllerReflector.php +++ b/src/Util/ControllerReflector.php @@ -36,7 +36,7 @@ public function __construct(ContainerInterface $container) */ public function getReflectionMethod($controller): ?\ReflectionMethod { - if (is_string($controller)) { + if (\is_string($controller)) { $controller = $this->getClassAndMethod($controller); } @@ -72,7 +72,7 @@ private function getClassAndMethod(string $controller): ?array $method = $matches[2]; if (!class_exists($class) && $this->container->has($class)) { - $class = get_class($this->container->get($class)); + $class = \get_class($this->container->get($class)); } return $this->controllers[$controller] = [$class, $method]; diff --git a/tests/Command/DumpCommandTest.php b/tests/Command/DumpCommandTest.php index 8a8cbab04..563c8bde4 100644 --- a/tests/Command/DumpCommandTest.php +++ b/tests/Command/DumpCommandTest.php @@ -37,9 +37,9 @@ public function testJson(array $jsonOptions, int $expectedJsonFlags): void public static function provideJsonMode(): \Generator { - yield 'pretty print' => [[], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES]; + yield 'pretty print' => [[], \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES]; - yield 'one line' => [['--no-pretty'], 0 | JSON_UNESCAPED_SLASHES]; + yield 'one line' => [['--no-pretty'], 0 | \JSON_UNESCAPED_SLASHES]; } public function testYaml(): void diff --git a/tests/Functional/Controller/MapQueryParameterController.php b/tests/Functional/Controller/MapQueryParameterController.php index da4ec9653..dc225a000 100644 --- a/tests/Functional/Controller/MapQueryParameterController.php +++ b/tests/Functional/Controller/MapQueryParameterController.php @@ -31,14 +31,14 @@ public function fetchArticleFromMapQueryParameter( #[OA\Response(response: '200', description: '')] public function fetchArticleFromMapQueryParameterValidateFilters( #[MapQueryParameter(options: ['min_range' => 2, 'max_range' => 1234])] int $minMaxInt, - #[MapQueryParameter(filter: FILTER_VALIDATE_DOMAIN)] string $domain, - #[MapQueryParameter(filter: FILTER_VALIDATE_EMAIL)] string $email, - #[MapQueryParameter(filter: FILTER_VALIDATE_IP)] string $ip, - #[MapQueryParameter(filter: FILTER_VALIDATE_IP, flags: FILTER_FLAG_IPV4)] string $ipv4, - #[MapQueryParameter(filter: FILTER_VALIDATE_IP, flags: FILTER_FLAG_IPV6)] string $ipv6, - #[MapQueryParameter(filter: FILTER_VALIDATE_MAC)] string $macAddress, - #[MapQueryParameter(filter: FILTER_VALIDATE_REGEXP, options: ['regexp' => '/^test/'])] string $regexp, - #[MapQueryParameter(filter: FILTER_VALIDATE_URL)] string $url, + #[MapQueryParameter(filter: \FILTER_VALIDATE_DOMAIN)] string $domain, + #[MapQueryParameter(filter: \FILTER_VALIDATE_EMAIL)] string $email, + #[MapQueryParameter(filter: \FILTER_VALIDATE_IP)] string $ip, + #[MapQueryParameter(filter: \FILTER_VALIDATE_IP, flags: \FILTER_FLAG_IPV4)] string $ipv4, + #[MapQueryParameter(filter: \FILTER_VALIDATE_IP, flags: \FILTER_FLAG_IPV6)] string $ipv6, + #[MapQueryParameter(filter: \FILTER_VALIDATE_MAC)] string $macAddress, + #[MapQueryParameter(filter: \FILTER_VALIDATE_REGEXP, options: ['regexp' => '/^test/'])] string $regexp, + #[MapQueryParameter(filter: \FILTER_VALIDATE_URL)] string $url, ) { } diff --git a/tests/Functional/ControllerTest.php b/tests/Functional/ControllerTest.php index 4c1e04bc0..f3bae6059 100644 --- a/tests/Functional/ControllerTest.php +++ b/tests/Functional/ControllerTest.php @@ -37,7 +37,7 @@ protected function setUp(): void protected function getOpenApiDefinition(string $area = 'default'): OA\OpenApi { - return $this->configurableContainerFactory->getContainer()->get(sprintf('nelmio_api_doc.generator.%s', $area))->generate(); + return $this->configurableContainerFactory->getContainer()->get(\sprintf('nelmio_api_doc.generator.%s', $area))->generate(); } /** @@ -179,13 +179,13 @@ public static function provideUniversalTestCases(): \Generator private static function getFixture(string $fixture): string { if (!file_exists($fixture)) { - self::fail(sprintf('The fixture file "%s" does not exist.', $fixture)); + self::fail(\sprintf('The fixture file "%s" does not exist.', $fixture)); } $content = file_get_contents($fixture); if (false === $content) { - self::fail(sprintf('Failed to read the fixture file "%s".', $fixture)); + self::fail(\sprintf('Failed to read the fixture file "%s".', $fixture)); } return $content; diff --git a/tests/Functional/Entity/VirtualProperty.php b/tests/Functional/Entity/VirtualProperty.php index 9593e1314..bf193e832 100644 --- a/tests/Functional/Entity/VirtualProperty.php +++ b/tests/Functional/Entity/VirtualProperty.php @@ -50,6 +50,6 @@ public function __call(string $name, array $arguments) return 'Success'; } - throw new \LogicException(sprintf('%s::__call does not implement this function.', __CLASS__)); + throw new \LogicException(\sprintf('%s::__call does not implement this function.', __CLASS__)); } } diff --git a/tests/Functional/TestKernel.php b/tests/Functional/TestKernel.php index 335402d72..cd9201f2d 100644 --- a/tests/Functional/TestKernel.php +++ b/tests/Functional/TestKernel.php @@ -219,7 +219,7 @@ class_exists(ApiProperty::class) 'html_config' => [ 'assets_mode' => AssetsMode::BUNDLE, ], - 'use_validation_groups' => boolval(self::USE_VALIDATION_GROUPS === $this->flag), + 'use_validation_groups' => self::USE_VALIDATION_GROUPS === $this->flag, 'documentation' => [ 'info' => [ 'title' => 'My Default App', diff --git a/tests/Functional/WebTestCase.php b/tests/Functional/WebTestCase.php index a54d26d50..a76cca085 100644 --- a/tests/Functional/WebTestCase.php +++ b/tests/Functional/WebTestCase.php @@ -28,7 +28,7 @@ protected static function createKernel(array $options = []): KernelInterface protected function getOpenApiDefinition(string $area = 'default'): OA\OpenApi { - return static::$kernel->getContainer()->get(sprintf('nelmio_api_doc.generator.%s', $area))->generate(); + return static::$kernel->getContainer()->get(\sprintf('nelmio_api_doc.generator.%s', $area))->generate(); } public function hasModel(string $name): bool @@ -43,7 +43,7 @@ protected function getModel(string $name): OA\Schema { $api = $this->getOpenApiDefinition(); $key = array_search($name, array_column($api->components->schemas, 'schema'), true); - static::assertNotFalse($key, sprintf('Model "%s" does not exist.', $name)); + static::assertNotFalse($key, \sprintf('Model "%s" does not exist.', $name)); return $api->components->schemas[$key]; } @@ -55,7 +55,7 @@ protected function getOperation(string $path, string $method): OA\Operation self::assertInstanceOf( OA\Operation::class, $path->{$method}, - sprintf('Operation "%s" for path "%s" does not exist', $method, $path->path) + \sprintf('Operation "%s" for path "%s" does not exist', $method, $path->path) ); return $path->{$method}; @@ -107,7 +107,7 @@ public function assertHasPath(string $path, OA\OpenApi $api): void static::assertContains( $path, $paths, - sprintf('Failed asserting that path "%s" does exist.', $path) + \sprintf('Failed asserting that path "%s" does exist.', $path) ); } @@ -117,7 +117,7 @@ public function assertNotHasPath(string $path, OA\OpenApi $api): void static::assertNotContains( $path, $paths, - sprintf('Failed asserting that path "%s" does not exist.', $path) + \sprintf('Failed asserting that path "%s" does not exist.', $path) ); } @@ -130,7 +130,7 @@ public function assertHasResponse($responseCode, OA\Operation $operation): void static::assertContains( $responseCode, $responses, - sprintf('Failed asserting that response "%s" does exist.', $responseCode) + \sprintf('Failed asserting that response "%s" does exist.', $responseCode) ); } @@ -145,7 +145,7 @@ public function assertHasParameter(string $name, string $in, OA\AbstractAnnotati static::assertNotEmpty( $parameters, - sprintf('Failed asserting that parameter "%s" in "%s" does exist.', $name, $in) + \sprintf('Failed asserting that parameter "%s" in "%s" does exist.', $name, $in) ); } @@ -158,7 +158,7 @@ public function assertNotHasParameter(string $name, string $in, OA\AbstractAnnot static::assertNotContains( $name, $parameters[$in] ?? [], - sprintf('Failed asserting that parameter "%s" in "%s" does not exist.', $name, $in) + \sprintf('Failed asserting that parameter "%s" in "%s" does not exist.', $name, $in) ); } @@ -171,7 +171,7 @@ public function assertHasProperty(string $property, OA\AbstractAnnotation $annot static::assertContains( $property, $properties, - sprintf('Failed asserting that property "%s" does exist.', $property) + \sprintf('Failed asserting that property "%s" does exist.', $property) ); } @@ -184,7 +184,7 @@ public function assertNotHasProperty(string $property, OA\AbstractAnnotation $an static::assertNotContains( $property, $properties, - sprintf('Failed asserting that property "%s" does not exist.', $property) + \sprintf('Failed asserting that property "%s" does not exist.', $property) ); } } diff --git a/tests/Model/ModelRegistryTest.php b/tests/Model/ModelRegistryTest.php index 9c0c0957c..7e87a4b96 100644 --- a/tests/Model/ModelRegistryTest.php +++ b/tests/Model/ModelRegistryTest.php @@ -235,7 +235,7 @@ public static function getNameAlternatives(): \Generator public function testUnsupportedTypeException(Type $type, string $stringType): void { $this->expectException('\LogicException'); - $this->expectExceptionMessage(sprintf('Schema of type "%s" can\'t be generated, no describer supports it.', $stringType)); + $this->expectExceptionMessage(\sprintf('Schema of type "%s" can\'t be generated, no describer supports it.', $stringType)); $registry = new ModelRegistry([], $this->createOpenApi()); $registry->register(new Model($type)); @@ -254,7 +254,7 @@ public function testUnsupportedTypeExceptionWithNonExistentClass(): void $type = new Type(Type::BUILTIN_TYPE_OBJECT, false, $className); $this->expectException(\LogicException::class); - $this->expectExceptionMessage(sprintf('Schema of type "\%s" can\'t be generated, no describer supports it. Class "\Some\Class\That\DoesNotExist" does not exist, did you forget a use statement, or typed it wrong?', $className)); + $this->expectExceptionMessage(\sprintf('Schema of type "\%s" can\'t be generated, no describer supports it. Class "\Some\Class\That\DoesNotExist" does not exist, did you forget a use statement, or typed it wrong?', $className)); $registry = new ModelRegistry([], $this->createOpenApi()); $registry->register(new Model($type)); diff --git a/tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php b/tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php index 0d50f044f..d74509685 100644 --- a/tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php +++ b/tests/ModelDescriber/Annotations/SymfonyConstraintAnnotationReaderTest.php @@ -99,7 +99,7 @@ public function testAssertChoiceResultsInNumericArray($entity): void public static function provideAssertChoiceResultsInNumericArray(): \Generator { - define('TEST_ASSERT_CHOICE_STATUSES', [ + \define('TEST_ASSERT_CHOICE_STATUSES', [ 1 => 'active', 2 => 'blocked', ]); diff --git a/tests/Render/RenderOpenApiTest.php b/tests/Render/RenderOpenApiTest.php index b9bcda55c..5da22671c 100644 --- a/tests/Render/RenderOpenApiTest.php +++ b/tests/Render/RenderOpenApiTest.php @@ -34,14 +34,14 @@ public function testRender(): void public function testUnknownFormat(): void { $availableOpenApiRenderers = []; - $this->expectExceptionObject(new \InvalidArgumentException(sprintf('Format "%s" is not supported.', self::FORMAT))); + $this->expectExceptionObject(new \InvalidArgumentException(\sprintf('Format "%s" is not supported.', self::FORMAT))); $this->renderOpenApi(...$availableOpenApiRenderers); } public function testUnknownArea(): void { $this->hasArea = false; - $this->expectExceptionObject(new \InvalidArgumentException(sprintf('Area "%s" is not supported.', self::AREA))); + $this->expectExceptionObject(new \InvalidArgumentException(\sprintf('Area "%s" is not supported.', self::AREA))); $this->renderOpenApi(); } diff --git a/tests/SwaggerPhp/UtilTest.php b/tests/SwaggerPhp/UtilTest.php index 3c281cbd3..f5d5548ee 100644 --- a/tests/SwaggerPhp/UtilTest.php +++ b/tests/SwaggerPhp/UtilTest.php @@ -46,7 +46,7 @@ class UtilTest extends TestCase private OA\OpenApi $rootAnnotation; - public function setUp(): void + protected function setUp(): void { parent::setUp(); @@ -57,11 +57,11 @@ public function setUp(): void static function ($errno, $errstr) { throw new \Exception($errstr, $errno); }, - E_ALL + \E_ALL ); } - public function tearDown(): void + protected function tearDown(): void { restore_error_handler(); } @@ -115,9 +115,9 @@ public function testCreateChildWithEmptyProperties(): void /** @var OA\Info $info */ $info = Util::createChild($this->rootAnnotation, OA\Info::class, $properties); - $properties = array_filter(\get_object_vars($info), function ($key) { - return 0 !== \strpos($key, '_'); - }, ARRAY_FILTER_USE_KEY); + $properties = array_filter(get_object_vars($info), function ($key) { + return !str_starts_with($key, '_'); + }, \ARRAY_FILTER_USE_KEY); self::assertEquals([Generator::UNDEFINED], array_unique(array_values($properties))); @@ -202,22 +202,22 @@ public function testSearchCollectionItem(): void $item2, ]; - self::assertSame(0, Util::searchCollectionItem($collection, \get_object_vars($item1))); - self::assertSame(1, Util::searchCollectionItem($collection, \get_object_vars($item2))); + self::assertSame(0, Util::searchCollectionItem($collection, get_object_vars($item1))); + self::assertSame(1, Util::searchCollectionItem($collection, get_object_vars($item2))); self::assertNull(Util::searchCollectionItem( $collection, - array_merge(\get_object_vars($item2), ['prop3' => 'foobar']) + array_merge(get_object_vars($item2), ['prop3' => 'foobar']) )); $search = ['baz' => 'foobar']; self::expectException(\Exception::class); self::expectExceptionMessage('Undefined property: stdClass::$baz'); - Util::searchCollectionItem($collection, array_merge(\get_object_vars($item2), $search)); + Util::searchCollectionItem($collection, array_merge(get_object_vars($item2), $search)); // no exception on empty collection - self::assertNull(Util::searchCollectionItem([], \get_object_vars($item2))); + self::assertNull(Util::searchCollectionItem([], get_object_vars($item2))); } /** @@ -247,7 +247,7 @@ public function testSearchIndexedCollectionItem(array $setup, array $asserts): v self::assertSame( $assert['index'], Util::searchIndexedCollectionItem($properties, $assert['key'], $assert['value']), - sprintf('Failed to get the correct index for %s', print_r($assert, true)) + \sprintf('Failed to get the correct index for %s', print_r($assert, true)) ); } } @@ -269,7 +269,7 @@ public function testGetIndexedCollectionItem(array $setup, array $asserts): void foreach ($items as $assert) { $itemParent = !isset($assert['components']) ? $parent : $parent->components; - self::assertTrue(is_a($assert['class'], OA\AbstractAnnotation::class, true), sprintf('Invalid class %s', $assert['class'])); + self::assertTrue(is_a($assert['class'], OA\AbstractAnnotation::class, true), \sprintf('Invalid class %s', $assert['class'])); $child = Util::getIndexedCollectionItem( $itemParent, $assert['class'], @@ -398,7 +398,7 @@ public function testGetChild(array $setup, array $asserts): void if (\array_key_exists('exceptionMessage', $assert)) { $this->expectExceptionMessage($assert['exceptionMessage']); } - self::assertTrue(is_a($assert['class'], OA\AbstractAnnotation::class, true), sprintf('Invalid class %s', $assert['class'])); + self::assertTrue(is_a($assert['class'], OA\AbstractAnnotation::class, true), \sprintf('Invalid class %s', $assert['class'])); $child = Util::getChild($parent, $assert['class'], $assert['props']); self::assertInstanceOf($assert['class'], $child); @@ -904,7 +904,7 @@ public function assertContextIsConnectedToRootContext(Context $context): void */ private function getSetupPropertiesWithoutClass(array $setup): array { - return array_filter($setup, function ($k) {return 'class' !== $k; }, ARRAY_FILTER_USE_KEY); + return array_filter($setup, function ($k) {return 'class' !== $k; }, \ARRAY_FILTER_USE_KEY); } /** @@ -912,11 +912,11 @@ private function getSetupPropertiesWithoutClass(array $setup): array */ private function getNonDefaultProperties(OA\AbstractAnnotation $object): array { - $objectVars = \get_object_vars($object); - $classVars = \get_class_vars(\get_class($object)); + $objectVars = get_object_vars($object); + $classVars = get_class_vars($object::class); $props = []; foreach ($objectVars as $key => $value) { - if ($value !== $classVars[$key] && 0 !== \strpos($key, '_')) { + if ($value !== $classVars[$key] && !str_starts_with($key, '_')) { $props[$key] = $value; } } diff --git a/tests/Util/ControllerReflectorTest.php b/tests/Util/ControllerReflectorTest.php index 36e204e4e..d747c8f70 100644 --- a/tests/Util/ControllerReflectorTest.php +++ b/tests/Util/ControllerReflectorTest.php @@ -23,11 +23,11 @@ public function testGetReflectionMethod(): void $controllerReflector = new ControllerReflector(new Container()); self::assertEquals( \ReflectionMethod::class, - get_class($controllerReflector->getReflectionMethod([BazingaController::class, 'userAction'])) + \get_class($controllerReflector->getReflectionMethod([BazingaController::class, 'userAction'])) ); self::assertEquals( \ReflectionMethod::class, - get_class($controllerReflector->getReflectionMethod(BazingaController::class.'::userAction')) + \get_class($controllerReflector->getReflectionMethod(BazingaController::class.'::userAction')) ); self::assertNull( $controllerReflector->getReflectionMethod('UnknownController::userAction')