Skip to content

Commit

Permalink
Assigning something other than $this in constructor is impure
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Apr 19, 2024
1 parent 1ab6c28 commit c9f5b1c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -655,6 +655,7 @@ private function processStmtNode(
&& $scope->getFunction() instanceof PhpMethodFromParserNodeReflection
&& $scope->getFunction()->getDeclaringClass()->hasConstructor()
&& $scope->getFunction()->getDeclaringClass()->getConstructor()->getName() === $scope->getFunction()->getName()
&& TypeUtils::findThisType($scope->getType($node->getPropertyFetch()->var)) !== null
) {
return;
}
Expand Down
4 changes: 4 additions & 0 deletions tests/PHPStan/Rules/Pure/PureMethodRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,10 @@ public function testPureConstructor(): void
'Method PureConstructor\Bar::__construct() is marked as impure but does not have any side effects.',
30,
],
[
'Impure property assignment in pure method PureConstructor\AssignOtherThanThis::__construct().',
49,
],
]);
}

Expand Down
13 changes: 13 additions & 0 deletions tests/PHPStan/Rules/Pure/data/pure-constructor.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,16 @@ public function __construct(
}

}

class AssignOtherThanThis
{
private int $i = 0;

/** @phpstan-pure */
public function __construct(
self $other,
)
{
$other->i = 1;
}
}

0 comments on commit c9f5b1c

Please sign in to comment.