Skip to content

Commit 644e923

Browse files
github-actions[bot]phpstan-bot
authored andcommitted
Fix false positives for is_a() and instanceof checks on $this in traits
- When analyzing trait methods, $this is bound to each using class separately - is_a($this, SomeClass::class) was reported as "always true" in SomeClass context and "always false" in SomeClass2 context, but both are false positives - Added trait-aware check in ImpossibleCheckTypeHelper to treat $this as uncertain when inside a trait, since the same code is shared across multiple classes - New regression test in tests/PHPStan/Rules/Comparison/data/bug-13023.php Closes phpstan/phpstan#13023
1 parent 54f3522 commit 644e923

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

src/Rules/Comparison/ImpossibleCheckTypeHelper.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,11 @@ public function findSpecifiedType(
310310
continue;
311311
}
312312

313+
if ($scope->isInTrait() && $sureType[0] instanceof Expr\Variable && $sureType[0]->name === 'this') {
314+
$results[] = TrinaryLogic::createMaybe();
315+
continue;
316+
}
317+
313318
if ($this->treatPhpDocTypesAsCertain) {
314319
$argumentType = $scope->getType($sureType[0]);
315320
} else {
@@ -336,6 +341,11 @@ public function findSpecifiedType(
336341
continue;
337342
}
338343

344+
if ($scope->isInTrait() && $sureNotType[0] instanceof Expr\Variable && $sureNotType[0]->name === 'this') {
345+
$results[] = TrinaryLogic::createMaybe();
346+
continue;
347+
}
348+
339349
if ($this->treatPhpDocTypesAsCertain) {
340350
$argumentType = $scope->getType($sureNotType[0]);
341351
} else {

tests/PHPStan/Rules/Comparison/ImpossibleCheckTypeFunctionCallRuleTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1207,4 +1207,10 @@ public function testBug13799(): void
12071207
]);
12081208
}
12091209

1210+
public function testBug13023(): void
1211+
{
1212+
$this->treatPhpDocTypesAsCertain = true;
1213+
$this->analyse([__DIR__ . '/data/bug-13023.php'], []);
1214+
}
1215+
12101216
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug13023;
4+
5+
class SomeClass
6+
{
7+
use MyTrait;
8+
}
9+
10+
class SomeClass2
11+
{
12+
use MyTrait;
13+
}
14+
15+
trait MyTrait
16+
{
17+
public function getRandom(): int
18+
{
19+
$value = random_int(1, 100);
20+
if (is_a($this, SomeClass::class)) {
21+
return $value * $value;
22+
}
23+
return $value;
24+
}
25+
}

0 commit comments

Comments
 (0)