Skip to content

Commit 1182199

Browse files
committed
TypeSpecifier - observe hasSideEffects() for static methods
1 parent f22c92d commit 1182199

3 files changed

Lines changed: 57 additions & 0 deletions

File tree

src/Analyser/TypeSpecifier.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1204,6 +1204,28 @@ public function create(
12041204
}
12051205
}
12061206

1207+
if (
1208+
$expr instanceof StaticCall
1209+
&& $expr->name instanceof Node\Identifier
1210+
&& $scope !== null
1211+
) {
1212+
$methodName = $expr->name->toString();
1213+
if ($expr->class instanceof Name) {
1214+
$calledOnType = $scope->resolveTypeByName($expr->class);
1215+
} else {
1216+
$calledOnType = $scope->getType($expr->class);
1217+
}
1218+
1219+
$methodReflection = $scope->getMethodReflection($calledOnType, $methodName);
1220+
if ($methodReflection === null || $methodReflection->hasSideEffects()->yes()) {
1221+
if (isset($resultType) && !TypeCombinator::containsNull($resultType)) {
1222+
return $this->createNullsafeTypes($rootExpr, $originalExpr, $scope, $context, $overwrite, $type);
1223+
}
1224+
1225+
return new SpecifiedTypes([], [], false, [], $rootExpr);
1226+
}
1227+
}
1228+
12071229
$sureTypes = [];
12081230
$sureNotTypes = [];
12091231
$exprString = $this->printer->prettyPrintExpr($expr);

tests/PHPStan/Analyser/NodeScopeResolverTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -894,6 +894,7 @@ public function dataFileAsserts(): iterable
894894
yield from $this->gatherAssertTypes(__DIR__ . '/data/non-empty-string-substr-specifying.php');
895895
yield from $this->gatherAssertTypes(__DIR__ . '/data/unset-conditional-expressions.php');
896896
yield from $this->gatherAssertTypes(__DIR__ . '/data/conditional-types-inference.php');
897+
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-7210.php');
897898
}
898899

899900
/**
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php
2+
3+
namespace Bug7210;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
class HelloWorld {
8+
public function doStuff(): void {
9+
if (self::getBool()) {
10+
return;
11+
}
12+
13+
assertType('bool', self::getBool());
14+
}
15+
16+
/** @phpstan-impure */
17+
private static function getBool(): bool {
18+
return mt_rand(0, 1) === 0;
19+
}
20+
}
21+
22+
class HelloWorld2 {
23+
public function doStuff(): void {
24+
if (self::getBool()) {
25+
return;
26+
}
27+
28+
assertType('false', self::getBool());
29+
}
30+
31+
private static function getBool(): bool {
32+
return mt_rand(0, 1) === 0;
33+
}
34+
}

0 commit comments

Comments
 (0)