Skip to content
Merged
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
11 changes: 11 additions & 0 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -3327,6 +3327,17 @@ public function filterBySpecifiedTypes(SpecifiedTypes $specifiedTypes): self
continue;
}

if (
!$typeSpecification['sure']
&& $expr instanceof Variable && is_string($expr->name)
&& $scope->hasVariableType($expr->name)->no()
) {
// removing type from a certainly-undefined variable cannot make
// it defined; a sure specification (e.g. is_string($a)) still can -
// the condition can only hold for a defined variable
continue;
}

if ($typeSpecification['sure']) {
if ($specifiedTypes->shouldOverwrite()) {
$scope = $scope->assignExpression($expr, $type, $type);
Expand Down
22 changes: 22 additions & 0 deletions tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1701,4 +1701,26 @@ public function testBug10090(): void
]);
}

public function testBug2032(): void
{
$this->cliArgumentsVariablesRegistered = true;
$this->polluteScopeWithLoopInitialAssignments = false;
$this->checkMaybeUndefinedVariables = true;
$this->polluteScopeWithAlwaysIterableForeach = true;
$this->analyse([__DIR__ . '/data/bug-2032.php'], [
[
'Undefined variable: $undefined',
6,
],
[
'Undefined variable: $undefined',
9,
],
[
'Undefined variable: $undefined',
15,
],
]);
}

}
17 changes: 17 additions & 0 deletions tests/PHPStan/Rules/Variables/data/bug-2032.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php declare(strict_types = 1);

namespace Bug2032;

function noloop(array $foo) {
if ($undefined) {}

foreach ($foo as $bar) {
if ($undefined) {}
}
}

function loop(array $foo) {
foreach ($foo as $bar) {
if ($undefined) {}
}
}
Loading