Skip to content

Commit

Permalink
Inline @var above property should not pollute scope inside methods
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Jan 23, 2021
1 parent 39b5a71 commit e832df4
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -2663,7 +2663,7 @@ private function enterFunctionLike(
bool $preserveThis
): self
{
$variableTypes = $this->getVariableTypes();
$variableTypes = [];
$nativeExpressionTypes = [];
foreach (ParametersAcceptorSelector::selectSingle($functionReflection->getVariants())->getParameters() as $parameter) {
$parameterType = $parameter->getType();
Expand All @@ -2674,8 +2674,8 @@ private function enterFunctionLike(
$nativeExpressionTypes[sprintf('$%s', $parameter->getName())] = $parameter->getNativeType();
}

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

return $this->scopeFactory->create(
Expand Down
4 changes: 4 additions & 0 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -2777,6 +2777,10 @@ private function processStmtVarAnnotation(MutatingScope $scope, Node\Stmt $stmt,
continue;
}

if ($scope->isInClass() && $scope->getFunction() === null) {
continue;
}

if ($scope->canAnyVariableExist()) {
$certainty = TrinaryLogic::createYes();
}
Expand Down
15 changes: 15 additions & 0 deletions tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -884,4 +884,19 @@ public function testBug3515(): void
]);
}

public function testBug4412(): void
{
$this->cliArgumentsVariablesRegistered = true;
$this->polluteScopeWithLoopInitialAssignments = false;
$this->polluteCatchScopeWithTryAssignments = false;
$this->checkMaybeUndefinedVariables = true;
$this->polluteScopeWithAlwaysIterableForeach = true;
$this->analyse([__DIR__ . '/data/bug-4412.php'], [
[
'Undefined variable: $a',
17,
],
]);
}

}
20 changes: 20 additions & 0 deletions tests/PHPStan/Rules/Variables/data/bug-4412.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Bug4412;

/**
* @phpstan-template T of \Exception
*/
class B
{
/** @var self<\Exception> $a */
public $a;

/**
* @phpstan-return T
*/
public function get() {
return $a->get();
}

}

0 comments on commit e832df4

Please sign in to comment.