Skip to content

Fix false positive unreachable statement #4112

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 21, 2025
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
2 changes: 1 addition & 1 deletion src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -6765,7 +6765,7 @@ private function getNextUnreachableStatements(array $nodes, bool $earlyBinding):
$stmts[] = $node;
continue;
}
if ($node instanceof Node\Stmt\Nop) {
if ($node instanceof Node\Stmt\Nop || $node instanceof Node\Stmt\InlineHTML) {
continue;
}
if (!$node instanceof Node\Stmt) {
Expand Down
11 changes: 11 additions & 0 deletions tests/PHPStan/Rules/DeadCode/UnreachableStatementRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,17 @@ public function testBug11992(): void
$this->analyse([__DIR__ . '/data/bug-11992.php'], []);
}

public function testBug7531(): void
{
$this->treatPhpDocTypesAsCertain = false;
$this->analyse([__DIR__ . '/data/bug-7531.php'], [
[
'Unreachable statement - code above always terminates.',
22,
],
]);
}

public function testMultipleUnreachable(): void
{
$this->treatPhpDocTypesAsCertain = true;
Expand Down
24 changes: 24 additions & 0 deletions tests/PHPStan/Rules/DeadCode/data/bug-7531.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php declare(strict_types = 1);

namespace Bug7531;

/** @var int $compareTo */

?>

<?php foreach ([1,2,3] as $number) : ?>
<?php if ($number > $compareTo) : ?>
<xs:sequence>some xml data</xs:sequence>
<?php else : ?>
<?php throw new \Exception("Unexpected behavior") ?>
<?php endif ?>
<?php endforeach; ?>

<?php foreach ([1,2,3] as $number) : ?>
<?php if ($number > $compareTo) : ?>
<xs:sequence>some xml data</xs:sequence>
<?php else : ?>
<?php throw new \Exception("Unexpected behavior") ?>
<?php throw new \Exception("Unreachable") ?>
<?php endif ?>
<?php endforeach; ?>
Loading