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
4 changes: 2 additions & 2 deletions src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -3732,7 +3732,7 @@ public function processFinallyScope(self $finallyScope, self $originalFinallySco
$finallyScope->nativeExpressionTypes,
$originalFinallyScope->nativeExpressionTypes,
),
$this->conditionalExpressions,
$this->intersectConditionalExpressions($finallyScope->conditionalExpressions),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are there even more places?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All 11,836 tests pass (79,345 assertions) and make phpstan reports no errors.

Summary of findings for the reviewer's question "are there even more places?":

No, there are no more places that need the fix. Here's the complete analysis:

The two methods already fixed in this PR are the only ones where stale conditional expressions could cause incorrect type narrowing:

  • processFinallyScope (line 3735) — already fixed
  • processAlwaysIterableForeachScopeWithoutPollute (line 3880) — already fixed

The remaining methods that pass $this->conditionalExpressions when creating a new scope fall into three safe categories:

  1. Only modify $this-related state (3 methods): enterClosureBind, restoreOriginalScopeAfterClosureBind, restoreThis — these only touch $this-prefixed expressions and inClosureBindScopeClasses, so variable alias conditional expressions (like $current => $initial) are unaffected.

  2. Results flow through mergeWith downstream (1 method): generalizeWith — every call site in NodeScopeResolver.php feeds the result into mergeWith, which already calls intersectConditionalExpressions, filtering out stale entries before they reach the final scope.

  3. Don't take another scope at all (~14 methods): toFiberScope, rememberConstructorScope, afterOpenSslCall, pushInFunctionCall, popInFunctionCall, enterClosureCall, enterExpressionAssign, exitExpressionAssign, etc. — these are simple state transitions on $this with no external scope to intersect with.

I wasn't able to post this as a comment on the PR (token lacks permission). The answer should be posted manually on #5435.

$this->inClosureBindScopeClasses,
$this->anonymousFunctionReflection,
$this->inFirstLevelStatement,
Expand Down Expand Up @@ -3877,7 +3877,7 @@ public function processAlwaysIterableForeachScopeWithoutPollute(self $finalScope
$this->getNamespace(),
$expressionTypes,
$nativeTypes,
$this->conditionalExpressions,
$this->intersectConditionalExpressions($finalScope->conditionalExpressions),
$this->inClosureBindScopeClasses,
$this->anonymousFunctionReflection,
$this->inFirstLevelStatement,
Expand Down
36 changes: 36 additions & 0 deletions tests/PHPStan/Analyser/Bug14446Test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php declare(strict_types = 1);

namespace PHPStan\Analyser;

use PHPStan\Testing\TypeInferenceTestCase;
use PHPUnit\Framework\Attributes\DataProvider;

class Bug14446Test extends TypeInferenceTestCase
{

public static function dataFileAsserts(): iterable
{
yield from self::gatherAssertTypes(__DIR__ . '/data/bug-14446.php');
}

/**
* @param mixed ...$args
*/
#[DataProvider('dataFileAsserts')]
public function testFileAsserts(
string $assertType,
string $file,
...$args,
): void
{
$this->assertFileAsserts($assertType, $file, ...$args);
}

public static function getAdditionalConfigFiles(): array
{
return [
__DIR__ . '/bug-14446.neon',
];
}

}
2 changes: 2 additions & 0 deletions tests/PHPStan/Analyser/bug-14446.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
parameters:
Copy link
Copy Markdown
Contributor

@staabm staabm Apr 10, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this test be in the strict-rule repo instead?
OverwriteVariablesWithForeachRuleTest

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. The change removes the OverwriteVariablesWithForeachRule service registration from tests/PHPStan/Analyser/bug-14446.neon, keeping only the polluteScopeWithAlwaysIterableForeach: false parameter. The rule belongs to the phpstan-strict-rules package and should be tested there via OverwriteVariablesWithForeachRuleTest. The type inference test (Bug14446Test) only needs the parameter setting, not the rule itself.

Both make phpstan (0 errors) and make tests (11,836 tests, 79,345 assertions) pass.

polluteScopeWithAlwaysIterableForeach: false
102 changes: 102 additions & 0 deletions tests/PHPStan/Analyser/data/bug-14446.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php declare(strict_types = 1);

namespace Bug14446;

use function PHPStan\Testing\assertType;

function test(bool $initial): void {
$current = $initial;

while (true) {
assertType('bool', $initial);
if (!$current) {
assertType('bool', $initial);
break;
}

$items = [1];
foreach ($items as $item) {
$current = false;
}
}

assertType('bool', $initial);
var_dump($initial === true);
}

function testMaybeIterable(bool $initial): void {
$current = $initial;

while (true) {
assertType('bool', $initial);
if (!$current) {
assertType('bool', $initial);
break;
}

$items = rand() > 0 ? [1] : [];
foreach ($items as $item) {
$current = false;
}
}

assertType('bool', $initial);
var_dump($initial === true);
}

function testFinally(bool $initial): void {
$current = $initial;
try {
// nothing
} finally {
$current = false;
}
assertType('false', $current);
assertType('bool', $initial);
if (!$current) {
assertType('bool', $initial);
}
}

function testFinallyWithCatch(bool $initial): void {
$current = $initial;
try {
doSomething();
} catch (\Exception $e) {
// nothing
} finally {
$current = false;
}
assertType('false', $current);
if (!$current) {
assertType('bool', $initial);
}
assertType('bool', $initial);
}

function doSomething(): void {}

/**
* @param mixed $value
*/
function testForeachKeyOverwrite($value): void {
if (is_array($value) && $value !== []) {
$hasOnlyStringKey = true;
foreach (array_keys($value) as $key) {
if (is_int($key)) {
$hasOnlyStringKey = false;
break;
}
}

assertType('bool', $hasOnlyStringKey);

if ($hasOnlyStringKey) {
// $key should not be in scope here with polluteScopeWithAlwaysIterableForeach: false
// Second foreach should not report "Foreach overwrites $key with its key variable"
foreach ($value as $key => $element) {
assertType('(int|string)', $key);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class StrictComparisonOfDifferentTypesRuleTest extends RuleTestCase

private bool $treatPhpDocTypesAsCertain = true;

private bool $polluteScopeWithAlwaysIterableForeach = true;

protected function getRule(): Rule
{
return new StrictComparisonOfDifferentTypesRule(
Expand All @@ -36,6 +38,11 @@ protected function shouldTreatPhpDocTypesAsCertain(): bool
return $this->treatPhpDocTypesAsCertain;
}

protected function shouldPolluteScopeWithAlwaysIterableForeach(): bool
{
return $this->polluteScopeWithAlwaysIterableForeach;
}

public function testStrictComparison(): void
{
$tipText = 'Because the type is coming from a PHPDoc, you can turn off this check by setting <fg=cyan>treatPhpDocTypesAsCertain: false</> in your <fg=cyan>%configurationFile%</>.';
Expand Down Expand Up @@ -1184,4 +1191,10 @@ public function testBug13421(): void
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-13421.php'], []);
}

public function testBug14446(): void
{
$this->polluteScopeWithAlwaysIterableForeach = false;
$this->analyse([__DIR__ . '/../../Analyser/data/bug-14446.php'], []);
}

}
Loading