Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
6 changes: 6 additions & 0 deletions rules.neon
Original file line number Diff line number Diff line change
Expand Up @@ -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
114 changes: 114 additions & 0 deletions src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Symfony;

use PhpParser\Node;
use PhpParser\Node\Expr\ArrowFunction;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\Variable;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor;
use PhpParser\NodeVisitorAbstract;
use function in_array;
use function is_string;

/**
* Collects the variables implicitly captured by an arrow function,
* including the ones needed by nested closures and arrow functions.
*/
final class ArrowFunctionCapturedVariablesVisitor extends NodeVisitorAbstract
{

/** @var list<string> */
private array $excludedNames;

/** @var array<string, Variable> */
private array $variables;

/**
* @param list<string> $excludedNames
* @param array<string, Variable> $variables
*/
private function __construct(array $excludedNames, array &$variables)
{
$this->excludedNames = $excludedNames;
$this->variables = &$variables;
}

/**
* @return array<string, Variable>
*/
public static function collect(ArrowFunction $arrowFunction): array
{
$variables = [];
self::collectInto($arrowFunction, [], $variables);

return $variables;
}

/**
* @param list<string> $excludedNames
* @param array<string, Variable> $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)

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.5, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitorAbstract::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.5, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitor::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.5, lowest)

PHPDoc tag `@return` contains unresolvable type.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.5, lowest)

Method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() has no return type specified.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.3, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitorAbstract::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.3, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitor::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.3, lowest)

PHPDoc tag `@return` contains unresolvable type.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.3, lowest)

Method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() has no return type specified.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.2, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitorAbstract::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.2, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitor::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.2, lowest)

PHPDoc tag `@return` contains unresolvable type.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.2, lowest)

Method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() has no return type specified.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitorAbstract::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitor::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, lowest)

PHPDoc tag `@return` contains unresolvable type.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, lowest)

Method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() has no return type specified.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.6, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitorAbstract::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.6, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitor::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.6, lowest)

PHPDoc tag `@return` contains unresolvable type.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.6, lowest)

Method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() has no return type specified.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.4, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitorAbstract::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.4, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitor::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.4, lowest)

PHPDoc tag `@return` contains unresolvable type.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.4, lowest)

Method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() has no return type specified.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitorAbstract::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitor::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, lowest)

PHPDoc tag `@return` contains unresolvable type.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, lowest)

Method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() has no return type specified.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitorAbstract::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, lowest)

Return type (mixed) of method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() should be covariant with return type (int|PhpParser\Node|null) of method PhpParser\NodeVisitor::enterNode()

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, lowest)

PHPDoc tag `@return` contains unresolvable type.

Check failure on line 71 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, lowest)

Method PHPStan\Rules\Symfony\ArrowFunctionCapturedVariablesVisitor::enterNode() has no return type specified.
{
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;

Check failure on line 85 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.5, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 85 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.3, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 85 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.2, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 85 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 85 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.6, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 85 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.4, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 85 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 85 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.
}

if ($node instanceof ArrowFunction) {
self::collectInto($node, $this->excludedNames, $this->variables);

return NodeVisitor::DONT_TRAVERSE_CHILDREN;

Check failure on line 91 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.5, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 91 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.3, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 91 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.2, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 91 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 91 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.6, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 91 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.4, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 91 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 91 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.
}

if ($node instanceof Node\Stmt\ClassLike) {
return NodeVisitor::DONT_TRAVERSE_CHILDREN;

Check failure on line 95 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.5, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 95 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.3, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 95 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.2, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 95 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.0, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 95 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.6, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 95 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.4, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 95 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (8.1, lowest)

Access to undefined constant PhpParser\NodeVisitor::DONT_TRAVERSE_CHILDREN.

Check failure on line 95 in src/Rules/Symfony/ArrowFunctionCapturedVariablesVisitor.php

View workflow job for this annotation

GitHub Actions / PHPStan (7.4, lowest)

Access to undefined constant PhpParser\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;
}

}
137 changes: 137 additions & 0 deletions src/Rules/Symfony/OptionsResolverCapturedOptionsRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Symfony;

use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\ArrowFunction;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\Variable;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ExtendedParameterReflection;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Symfony\CallArgumentClosureVisitor;
use PHPStan\Type\ObjectType;
use PHPStan\Type\TypeUtils;
use PHPStan\Type\VerbosityLevel;
use function count;
use function is_string;
use function sprintf;

/**
* Reports closures capturing the Options object passed to OptionsResolver lazy defaults and normalizers.
*
* Reading options from a closure invoked later bypasses the cycle detection of the OptionsResolver.
*
* @implements Rule<Expr>
*/
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<string, Variable>
*/
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);
}

}
42 changes: 42 additions & 0 deletions src/Symfony/CallArgumentClosureVisitor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php declare(strict_types = 1);

namespace PHPStan\Symfony;

use PhpParser\Node;
use PhpParser\NodeVisitorAbstract;

/**
* Marks closures and arrow functions passed directly as an argument of a call,
* and the ones invoked immediately after their definition.
*/
final class CallArgumentClosureVisitor extends NodeVisitorAbstract
{

public const CALL_ARGUMENT_ATTRIBUTE_NAME = 'phpstanSymfonyIsCallArgument';
public const IMMEDIATELY_INVOKED_ATTRIBUTE_NAME = 'phpstanSymfonyIsImmediatelyInvoked';

public function enterNode(Node $node): ?Node
{
if (!$node instanceof Node\Expr\CallLike || $node->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;
}

}
54 changes: 54 additions & 0 deletions tests/Rules/Symfony/OptionsResolverCapturedOptionsRuleTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Symfony;

use PHPStan\Rules\Rule;
use PHPStan\Testing\RuleTestCase;
use function interface_exists;

/**
* @extends RuleTestCase<OptionsResolverCapturedOptionsRule>
*/
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',
];
}

}
Loading
Loading