diff --git a/src/Analyzer/Analysis/ConstructorAnalysis.php b/src/Analyzer/Analysis/ConstructorAnalysis.php index 9d714cd8..97c174b9 100644 --- a/src/Analyzer/Analysis/ConstructorAnalysis.php +++ b/src/Analyzer/Analysis/ConstructorAnalysis.php @@ -110,17 +110,17 @@ public function getConstructorPromotableAssignments(): array $closeBrace = $this->tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openBrace); $variables = []; + $variablesWithAssignments = []; $properties = []; $propertyToVariableMap = []; - for ($index = $openBrace + 1; $index < $closeBrace; $index++) { - if (!$this->tokens[$index]->isGivenKind(\T_VARIABLE)) { - continue; - } - + foreach ($this->tokens->findGivenKind(\T_VARIABLE, $openBrace, $closeBrace) as $index => $token) { $semicolonIndex = $this->tokens->getNextMeaningfulToken($index); \assert(\is_int($semicolonIndex)); if (!$this->tokens[$semicolonIndex]->equals(';')) { + if ($this->tokens[$semicolonIndex]->equals('=')) { + $variablesWithAssignments[] = $token->getContent(); + } continue; } @@ -129,8 +129,12 @@ public function getConstructorPromotableAssignments(): array continue; } + if (\in_array($token->getContent(), $variablesWithAssignments, true)) { + continue; + } + $properties[$propertyIndex] = $this->tokens[$propertyIndex]->getContent(); - $variables[$index] = $this->tokens[$index]->getContent(); + $variables[$index] = $token->getContent(); $propertyToVariableMap[$propertyIndex] = $index; } diff --git a/tests/Analyzer/Analysis/ConstructorAnalysisTest.php b/tests/Analyzer/Analysis/ConstructorAnalysisTest.php index 2f8437a9..da58b18e 100644 --- a/tests/Analyzer/Analysis/ConstructorAnalysisTest.php +++ b/tests/Analyzer/Analysis/ConstructorAnalysisTest.php @@ -255,5 +255,19 @@ public function __construct($x) { } }', ]; + + yield 'with assignment of parameter' => [ + ['$x' => 30, '$z' => 68], + 'x = $x; + if (someCondition()) { + $y = -1; + } + $this->y = $y; + $this->z = $z; + } + }', + ]; } } diff --git a/tests/Fixer/PromotedConstructorPropertyFixerTest.php b/tests/Fixer/PromotedConstructorPropertyFixerTest.php index 3b13892c..9cc52092 100644 --- a/tests/Fixer/PromotedConstructorPropertyFixerTest.php +++ b/tests/Fixer/PromotedConstructorPropertyFixerTest.php @@ -927,6 +927,26 @@ public function __construct(int $x, int $y, int $z, bool $condition) ', ]; + yield 'do not promote when there is assignment to variable' => [ + <<<'PHP' + value = $value; + } + } + + PHP, + ]; + yield 'promote nullable types' => [ ' [ + yield 'promote single property when property is declared last' => [ '