Skip to content

Commit 72d2f3b

Browse files
committed
Fix calling getVariableType without checking hasVariableType first
1 parent e6a3b1f commit 72d2f3b

File tree

3 files changed

+44
-5
lines changed

3 files changed

+44
-5
lines changed

src/Analyser/MutatingScope.php

+15-5
Original file line numberDiff line numberDiff line change
@@ -2010,11 +2010,21 @@ static function (Node $node, Scope $scope) use ($arrowScope, &$arrowFunctionImpu
20102010

20112011
$nameType = $this->getType($node->name);
20122012
if (count($nameType->getConstantStrings()) > 0) {
2013-
return TypeCombinator::union(
2014-
...array_map(fn ($constantString) => $this
2015-
->filterByTruthyValue(new BinaryOp\Identical($node->name, new String_($constantString->getValue())))
2016-
->getVariableType($constantString->getValue()), $nameType->getConstantStrings()),
2017-
);
2013+
$types = [];
2014+
foreach ($nameType->getConstantStrings() as $constantString) {
2015+
$variableScope = $this
2016+
->filterByTruthyValue(
2017+
new BinaryOp\Identical($node->name, new String_($constantString->getValue())),
2018+
);
2019+
if ($variableScope->hasVariableType($constantString->getValue())->no()) {
2020+
$types[] = new ErrorType();
2021+
continue;
2022+
}
2023+
2024+
$types[] = $variableScope->getVariableType($constantString->getValue());
2025+
}
2026+
2027+
return TypeCombinator::union(...$types);
20182028
}
20192029
}
20202030

tests/PHPStan/Analyser/AnalyserIntegrationTest.php

+10
Original file line numberDiff line numberDiff line change
@@ -896,6 +896,16 @@ public function testBug7500(): void
896896
$this->assertNoErrors($errors);
897897
}
898898

899+
public function testBug12767(): void
900+
{
901+
$errors = $this->runAnalyse(__DIR__ . '/data/bug-12767.php');
902+
$this->assertCount(3, $errors);
903+
904+
$this->assertSame('Expected type int, actual: *ERROR*', $errors[0]->getMessage());
905+
$this->assertSame('Undefined variable: $field1', $errors[1]->getMessage());
906+
$this->assertSame('Undefined variable: $field2', $errors[2]->getMessage());
907+
}
908+
899909
public function testBug7554(): void
900910
{
901911
$errors = $this->runAnalyse(__DIR__ . '/data/bug-7554.php');
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
namespace Bug12767;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
class SkipDynamicVariable
8+
{
9+
public function bar(): void
10+
{
11+
$employee = (object) ['data' => ['dd1' => 1, 'dd2' => 2]];
12+
13+
for ($i=1; $i <= 2; $i++) {
14+
${'field'.$i} = $employee->data['dd'.$i];
15+
16+
assertType('int', ${'field'.$i});
17+
}
18+
}
19+
}

0 commit comments

Comments
 (0)