Skip to content

Commit

Permalink
style: [5.x] use @Symfony:risky ruleset (#2397)
Browse files Browse the repository at this point in the history
## 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`)
  • Loading branch information
DjordyKoert authored Nov 15, 2024
1 parent 6217051 commit 8e4802b
Show file tree
Hide file tree
Showing 61 changed files with 209 additions and 207 deletions.
2 changes: 2 additions & 0 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@
->exclude('tests/Functional/cache');

return (new PhpCsFixer\Config())
->setRiskyAllowed(true)
->setRules([
'@Symfony' => true,
'@Symfony:risky' => true,
'header_comment' => [
'header' => <<<HEADER
This file is part of the NelmioApiDocBundle package.
Expand Down
8 changes: 4 additions & 4 deletions src/Attribute/Areas.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ final class Areas
*/
public function __construct(array $properties)
{
if (!array_key_exists('value', $properties) || !is_array($properties['value'])) {
if (!\array_key_exists('value', $properties) || !\is_array($properties['value'])) {
$properties['value'] = array_values($properties);
}

Expand All @@ -32,11 +32,11 @@ public function __construct(array $properties)

$areas = [];
foreach ($properties['value'] as $area) {
if (!is_string($area)) {
if (!\is_string($area)) {
throw new \InvalidArgumentException('An area must be given as a string');
}

if (!in_array($area, $areas, true)) {
if (!\in_array($area, $areas, true)) {
$areas[] = $area;
}
}
Expand All @@ -46,6 +46,6 @@ public function __construct(array $properties)

public function has(string $area): bool
{
return in_array($area, $this->areas, true);
return \in_array($area, $this->areas, true);
}
}
2 changes: 1 addition & 1 deletion src/Command/DumpCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']),
Expand Down
2 changes: 1 addition & 1 deletion src/Controller/DocumentationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
}
4 changes: 2 additions & 2 deletions src/Controller/SwaggerUiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
2 changes: 1 addition & 1 deletion src/Controller/YamlDocumentationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}
}
2 changes: 1 addition & 1 deletion src/DependencyInjection/Compiler/TagDescribersPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down Expand Up @@ -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()
Expand Down
36 changes: 18 additions & 18 deletions src/DependencyInjection/NelmioApiDocExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,61 +82,61 @@ 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']])
->addMethodCall('setLogger', [new Reference('logger')])
->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))
Expand All @@ -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')
Expand Down Expand Up @@ -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 = [];
Expand Down
4 changes: 2 additions & 2 deletions src/Describer/ApiPlatformDescriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions src/Describer/ExternalDocDescriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 3 additions & 3 deletions src/Describer/OpenApiPhpDescriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand All @@ -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) {
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/Describer/RouteDescriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
10 changes: 5 additions & 5 deletions src/Model/ModelRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand All @@ -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);
}
Expand All @@ -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]),
]);
Expand Down
6 changes: 3 additions & 3 deletions src/ModelDescriber/Annotations/ReflectionReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

Expand Down Expand Up @@ -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;
}

Expand Down
Loading

0 comments on commit 8e4802b

Please sign in to comment.