Skip to content

Commit e832df4

Browse files
committed
Inline @var above property should not pollute scope inside methods
1 parent 39b5a71 commit e832df4

File tree

4 files changed

+42
-3
lines changed

4 files changed

+42
-3
lines changed

src/Analyser/MutatingScope.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2663,7 +2663,7 @@ private function enterFunctionLike(
26632663
bool $preserveThis
26642664
): self
26652665
{
2666-
$variableTypes = $this->getVariableTypes();
2666+
$variableTypes = [];
26672667
$nativeExpressionTypes = [];
26682668
foreach (ParametersAcceptorSelector::selectSingle($functionReflection->getVariants())->getParameters() as $parameter) {
26692669
$parameterType = $parameter->getType();
@@ -2674,8 +2674,8 @@ private function enterFunctionLike(
26742674
$nativeExpressionTypes[sprintf('$%s', $parameter->getName())] = $parameter->getNativeType();
26752675
}
26762676

2677-
if (!$preserveThis && array_key_exists('this', $variableTypes)) {
2678-
unset($variableTypes['this']);
2677+
if ($preserveThis && array_key_exists('this', $this->variableTypes)) {
2678+
$variableTypes['this'] = $this->variableTypes['this'];
26792679
}
26802680

26812681
return $this->scopeFactory->create(

src/Analyser/NodeScopeResolver.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2777,6 +2777,10 @@ private function processStmtVarAnnotation(MutatingScope $scope, Node\Stmt $stmt,
27772777
continue;
27782778
}
27792779

2780+
if ($scope->isInClass() && $scope->getFunction() === null) {
2781+
continue;
2782+
}
2783+
27802784
if ($scope->canAnyVariableExist()) {
27812785
$certainty = TrinaryLogic::createYes();
27822786
}

tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -884,4 +884,19 @@ public function testBug3515(): void
884884
]);
885885
}
886886

887+
public function testBug4412(): void
888+
{
889+
$this->cliArgumentsVariablesRegistered = true;
890+
$this->polluteScopeWithLoopInitialAssignments = false;
891+
$this->polluteCatchScopeWithTryAssignments = false;
892+
$this->checkMaybeUndefinedVariables = true;
893+
$this->polluteScopeWithAlwaysIterableForeach = true;
894+
$this->analyse([__DIR__ . '/data/bug-4412.php'], [
895+
[
896+
'Undefined variable: $a',
897+
17,
898+
],
899+
]);
900+
}
901+
887902
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?php
2+
3+
namespace Bug4412;
4+
5+
/**
6+
* @phpstan-template T of \Exception
7+
*/
8+
class B
9+
{
10+
/** @var self<\Exception> $a */
11+
public $a;
12+
13+
/**
14+
* @phpstan-return T
15+
*/
16+
public function get() {
17+
return $a->get();
18+
}
19+
20+
}

0 commit comments

Comments
 (0)