Skip to content

Commit

Permalink
Conditional expressions - do not take conclusions about identical var…
Browse files Browse the repository at this point in the history
…iable in assignment
  • Loading branch information
ondrejmirtes committed Jan 3, 2023
1 parent dc77608 commit cde53d1
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Analyser/NodeScopeResolver.php
Expand Up @@ -3795,6 +3795,10 @@ private function processSureTypesForConditionalExpressionsAfterAssign(Scope $sco
continue;
}

if ($expr->name === $variableName) {
continue;
}

if (!isset($conditionalExpressions[$exprString])) {
$conditionalExpressions[$exprString] = [];
}
Expand Down Expand Up @@ -3825,6 +3829,10 @@ private function processSureNotTypesForConditionalExpressionsAfterAssign(Scope $
continue;
}

if ($expr->name === $variableName) {
continue;
}

if (!isset($conditionalExpressions[$exprString])) {
$conditionalExpressions[$exprString] = [];
}
Expand Down
2 changes: 2 additions & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Expand Up @@ -1157,6 +1157,8 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-8568.php');
yield from $this->gatherAssertTypes(__DIR__ . '/../Rules/DeadCode/data/bug-8620.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-8635.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-8625.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-8621.php');
}

/**
Expand Down
27 changes: 27 additions & 0 deletions tests/PHPStan/Analyser/data/bug-8621.php
@@ -0,0 +1,27 @@
<?php

namespace Bug8621;

use function PHPStan\Testing\assertType;

class HelloWorld
{
/**
* @param array<string> $data
*/
public function rows (array $data): void
{
$even = true;

echo "<table>";
foreach ($data as $datum)
{
$even = !$even;
assertType('bool', $even);

echo "<tr class='" . ($even ? 'even' :'odd') . "'>";
echo "<td>{$datum}</td></tr>";
}
echo "</table>";
}
}
23 changes: 23 additions & 0 deletions tests/PHPStan/Analyser/data/bug-8625.php
@@ -0,0 +1,23 @@
<?php

namespace Bug8625;

use function PHPStan\Testing\assertType;

class HelloWorld
{
public static function sayHello(): void
{
$key = false;
$loopArray = [1, 2, 3];
foreach ($loopArray as $i) {
$key = $key === false;
assertType('bool', $key);
if ($key) {
echo "i=$i key is true\n";
} else {
echo "i=$i key is false\n";
}
}
}
}

0 comments on commit cde53d1

Please sign in to comment.