diff --git a/README.md b/README.md index 5e0895aa..0f084c54 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ This extension provides following features: * Notifies you when you try to get a private service from the container. * Notifies you when you access undefined console command arguments or options. * Validates default values of console command arguments and options. +* Notifies you when a closure captures the `Options` object of an `OptionsResolver` lazy default or normalizer, which bypasses the detection of circular option dependencies. * Recognizes `@required` annotation and `#[Required]` attribute for autowiring properties and methods. * Optionally correct return types for `InputInterface::getArgument()`, `::getOption()`, `::getOptions()`, `::hasArgument()`, and `::hasOption()`. * Optionally provides correct return type for `Command::getHelper()` method. diff --git a/composer.json b/composer.json index c70910ea..fec15253 100644 --- a/composer.json +++ b/composer.json @@ -34,6 +34,7 @@ "symfony/framework-bundle": "^5.4 || ^6.1", "symfony/http-foundation": "^5.4 || ^6.1", "symfony/messenger": "^5.4", + "symfony/options-resolver": "^5.4 || ^6.1 || ^7.4 || ^8.1", "symfony/polyfill-php80": "^1.24", "symfony/serializer": "^5.4", "symfony/service-contracts": "^2.2.0" diff --git a/rules.neon b/rules.neon index cedcea7a..70292c0b 100644 --- a/rules.neon +++ b/rules.neon @@ -5,4 +5,10 @@ rules: - PHPStan\Rules\Symfony\InvalidArgumentDefaultValueRule - PHPStan\Rules\Symfony\UndefinedOptionRule - PHPStan\Rules\Symfony\InvalidOptionDefaultValueRule + - PHPStan\Rules\Symfony\OptionsResolverCapturedOptionsRule +services: + - + class: PHPStan\Symfony\CallArgumentClosureVisitor + tags: + - phpstan.parser.richParserNodeVisitor diff --git a/src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php b/src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php new file mode 100644 index 00000000..73ecc313 --- /dev/null +++ b/src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php @@ -0,0 +1,114 @@ + */ + private array $excludedNames; + + /** @var array */ + private array $variables; + + /** + * @param list $excludedNames + * @param array $variables + */ + private function __construct(array $excludedNames, array &$variables) + { + $this->excludedNames = $excludedNames; + $this->variables = &$variables; + } + + /** + * @return array + */ + public static function collect(ArrowFunction $arrowFunction): array + { + $variables = []; + self::collectInto($arrowFunction, [], $variables); + + return $variables; + } + + /** + * @param list $excludedNames + * @param array $variables + */ + private static function collectInto(ArrowFunction $arrowFunction, array $excludedNames, array &$variables): void + { + foreach ($arrowFunction->params as $param) { + if (!$param->var instanceof Variable || !is_string($param->var->name)) { + continue; + } + + $excludedNames[] = $param->var->name; + } + + $traverser = new NodeTraverser(); + $traverser->addVisitor(new self($excludedNames, $variables)); + $traverser->traverse([$arrowFunction->expr]); + } + + /** + * @return NodeVisitor::DONT_TRAVERSE_CHILDREN|null + */ + public function enterNode(Node $node) + { + if ($node instanceof Variable) { + $this->addVariable($node); + + return null; + } + + if ($node instanceof Closure) { + // Only the variables imported by the closure are needed from the outer scope. + foreach ($node->uses as $use) { + $this->addVariable($use->var); + } + + return NodeVisitor::DONT_TRAVERSE_CHILDREN; + } + + if ($node instanceof ArrowFunction) { + self::collectInto($node, $this->excludedNames, $this->variables); + + return NodeVisitor::DONT_TRAVERSE_CHILDREN; + } + + if ($node instanceof Node\Stmt\ClassLike) { + return NodeVisitor::DONT_TRAVERSE_CHILDREN; + } + + return null; + } + + private function addVariable(Variable $variable): void + { + if (!is_string($variable->name) || $variable->name === 'this') { + return; + } + + if (in_array($variable->name, $this->excludedNames, true) || isset($this->variables[$variable->name])) { + return; + } + + $this->variables[$variable->name] = $variable; + } + +} diff --git a/src/Rules/Symfony/OptionsResolverCapturedOptionsRule.php b/src/Rules/Symfony/OptionsResolverCapturedOptionsRule.php new file mode 100644 index 00000000..aa5045c8 --- /dev/null +++ b/src/Rules/Symfony/OptionsResolverCapturedOptionsRule.php @@ -0,0 +1,137 @@ + + */ +final class OptionsResolverCapturedOptionsRule implements Rule +{ + + private const OPTIONS_CLASS = 'Symfony\Component\OptionsResolver\Options'; + private const OPTIONS_RESOLVER_CLASS = 'Symfony\Component\OptionsResolver\OptionsResolver'; + + public function getNodeType(): string + { + return Expr::class; + } + + public function processNode(Node $node, Scope $scope): array + { + if (!$node instanceof Closure && !$node instanceof ArrowFunction) { + return []; + } + + if ($this->isImmediatelyInvoked($node, $scope)) { + return []; + } + + $optionsType = new ObjectType(self::OPTIONS_CLASS); + $optionsResolverType = new ObjectType(self::OPTIONS_RESOLVER_CLASS); + + $errors = []; + foreach ($this->getCapturedVariables($node) as $name => $variable) { + if ($scope->hasVariableType($name)->no()) { + continue; + } + + $type = $scope->getType($variable); + if (!$optionsType->isSuperTypeOf($type)->yes() || $optionsResolverType->isSuperTypeOf($type)->yes()) { + continue; + } + + $errors[] = RuleErrorBuilder::message(sprintf( + 'Variable $%s of type %s must not be captured by a closure, as reading options lazily bypasses the OptionsResolver cycle detection.', + $name, + $type->describe(VerbosityLevel::typeOnly()), + )) + ->line($variable->getStartLine()) + ->tip('Read the needed options before defining the closure and capture the resolved values instead.') + ->identifier('symfonyOptionsResolver.optionsCaptured') + ->build(); + } + + return $errors; + } + + /** + * @param Closure|ArrowFunction $node + */ + private function isImmediatelyInvoked(Expr $node, Scope $scope): bool + { + if ($node->getAttribute(CallArgumentClosureVisitor::IMMEDIATELY_INVOKED_ATTRIBUTE_NAME) === true) { + return true; + } + + if ($node->getAttribute(CallArgumentClosureVisitor::CALL_ARGUMENT_ATTRIBUTE_NAME) !== true) { + return false; + } + + // The scope of a closure passed as argument knows the parameter receiving it. + $callStack = $scope->getFunctionCallStackWithParameters(); + if (count($callStack) === 0) { + return false; + } + + [$callee, $parameter] = $callStack[count($callStack) - 1]; + if ($parameter === null) { + return false; + } + + // Same logic as PHPStan's NodeScopeResolver::callCallbackImmediately() + if ($parameter instanceof ExtendedParameterReflection) { + $isImmediatelyInvoked = $parameter->isImmediatelyInvokedCallable(); + if (!$isImmediatelyInvoked->maybe()) { + return $isImmediatelyInvoked->yes(); + } + } + + return $callee instanceof FunctionReflection && TypeUtils::findCallableType($parameter->getType()) !== null; + } + + /** + * @param Closure|ArrowFunction $node + * @return array + */ + private function getCapturedVariables(Expr $node): array + { + $variables = []; + + if ($node instanceof Closure) { + foreach ($node->uses as $use) { + if (!is_string($use->var->name)) { + continue; + } + + $variables[$use->var->name] = $use->var; + } + + return $variables; + } + + return ArrowFunctionCapturedVariablesVisitor::collect($node); + } + +} diff --git a/src/Symfony/CallArgumentClosureVisitor.php b/src/Symfony/CallArgumentClosureVisitor.php new file mode 100644 index 00000000..3367aa45 --- /dev/null +++ b/src/Symfony/CallArgumentClosureVisitor.php @@ -0,0 +1,42 @@ +isFirstClassCallable()) { + return null; + } + + if ( + $node instanceof Node\Expr\FuncCall + && ($node->name instanceof Node\Expr\Closure || $node->name instanceof Node\Expr\ArrowFunction) + ) { + $node->name->setAttribute(self::IMMEDIATELY_INVOKED_ATTRIBUTE_NAME, true); + } + + foreach ($node->getArgs() as $arg) { + if (!$arg->value instanceof Node\Expr\Closure && !$arg->value instanceof Node\Expr\ArrowFunction) { + continue; + } + + $arg->value->setAttribute(self::CALL_ARGUMENT_ATTRIBUTE_NAME, true); + } + + return null; + } + +} diff --git a/tests/Rules/Symfony/OptionsResolverCapturedOptionsRuleTest.php b/tests/Rules/Symfony/OptionsResolverCapturedOptionsRuleTest.php new file mode 100644 index 00000000..dcd30336 --- /dev/null +++ b/tests/Rules/Symfony/OptionsResolverCapturedOptionsRuleTest.php @@ -0,0 +1,54 @@ + + */ +final class OptionsResolverCapturedOptionsRuleTest extends RuleTestCase +{ + + protected function getRule(): Rule + { + return new OptionsResolverCapturedOptionsRule(); + } + + public function testRule(): void + { + if (!interface_exists('Symfony\Component\OptionsResolver\Options')) { + self::markTestSkipped('Symfony OptionsResolver component is not available.'); + } + + $message = 'Variable $options of type Symfony\Component\OptionsResolver\Options must not be captured by a closure, as reading options lazily bypasses the OptionsResolver cycle detection.'; + $tip = 'Read the needed options before defining the closure and capture the resolved values instead.'; + + $this->analyse( + [ + __DIR__ . '/data/options-resolver-captured-options.php', + ], + [ + [$message, 15, $tip], + [$message, 21, $tip], + [$message, 25, $tip], + [$message, 30, $tip], + [$message, 33, $tip], + [$message, 36, $tip], + [$message, 36, $tip], + [$message, 39, $tip], + [$message, 43, $tip], + ], + ); + } + + public static function getAdditionalConfigFiles(): array + { + return [ + __DIR__ . '/options_resolver.neon', + ]; + } + +} diff --git a/tests/Rules/Symfony/data/options-resolver-captured-options.php b/tests/Rules/Symfony/data/options-resolver-captured-options.php new file mode 100644 index 00000000..7c66f6e7 --- /dev/null +++ b/tests/Rules/Symfony/data/options-resolver-captured-options.php @@ -0,0 +1,105 @@ +setDefault('closure_use', function (Options $options) { + return function () use ($options) { + return $options['a']; + }; + }); + + $resolver->setDefault('arrow_function', function (Options $options) { + return fn () => $options['a']; + }); + + $resolver->setDefault('by_reference', function (Options $options) { + return function () use (&$options) { + return $options['a']; + }; + }); + + $resolver->setNormalizer('normalizer', fn (Options $options, $value) => fn () => $options['a'] . $value); + + $resolver->setDefault('delayed_method_parameter', function (Options $options) { + return $this->delayed(fn () => $options['a']); + }); + + $resolver->setDefault('nested_arrow_functions', fn (Options $options) => fn () => fn () => $options['a']); + + $resolver->setDefault('arrow_function_wrapping_immediately_invoked_callback', function (Options $options) { + return fn (array $keys) => array_map(fn ($key) => $options[$key], $keys); + }); + + $resolver->setDefault('nested_in_argument', function (Options $options) { + return array_map('strval', [fn () => $options['a']]); + }); + + // No errors below + + $resolver->setDefault('resolved_value', function (Options $options) { + $a = $options['a']; + + return fn () => $a; + }); + + $resolver->setDefault('nested', function (OptionsResolver $nestedResolver) { + return fn () => $nestedResolver; + }); + + $resolver->setDefault('array_map', function (Options $options) { + return array_map(fn ($key) => $options[$key], ['a', 'b']); + }); + + $resolver->setDefault('array_map_closure', function (Options $options) { + return array_map(function ($key) use ($options) { + return $options[$key]; + }, ['a', 'b']); + }); + + $resolver->setDefault('immediately_invoked_closure', function (Options $options) { + return (function () use ($options) { + return $options['a']; + })(); + }); + + $resolver->setDefault('immediately_invoked_arrow_function', function (Options $options) { + return (fn () => $options['a'])(); + }); + + $resolver->setDefault('immediate_method_parameter', function (Options $options) { + return $this->immediate(fn () => $options['a']); + }); + + $resolver->setDefault('shadowing_parameter', function (Options $options) { + return fn (string $options) => $options; + }); + } + + /** + * @param callable(): mixed $callback + */ + private function delayed(callable $callback): callable + { + return $callback; + } + + /** + * @param-immediately-invoked-callable $callback + * @param callable(): mixed $callback + * @return mixed + */ + private function immediate(callable $callback) + { + return $callback(); + } + +} diff --git a/tests/Rules/Symfony/options_resolver.neon b/tests/Rules/Symfony/options_resolver.neon new file mode 100644 index 00000000..6655ad00 --- /dev/null +++ b/tests/Rules/Symfony/options_resolver.neon @@ -0,0 +1,5 @@ +services: + - + class: PHPStan\Symfony\CallArgumentClosureVisitor + tags: + - phpstan.parser.richParserNodeVisitor