Skip to content

Commit 0bf243c

Browse files
authored
forbidPhpDocNullabilityMismatchWithNativeTypehint: fix template handling (#71)
* ForbidPhpDocNullabilityMismatchWithNativeTypehintRule: fix template handling * improve test
1 parent 0c185ae commit 0bf243c

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/Rule/ForbidPhpDocNullabilityMismatchWithNativeTypehintRule.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
use PhpParser\Node\Expr\Variable;
77
use PhpParser\Node\FunctionLike;
88
use PhpParser\Node\Param;
9+
use PhpParser\Node\Stmt\ClassMethod;
10+
use PhpParser\Node\Stmt\Function_;
911
use PhpParser\Node\Stmt\Property;
1012
use PHPStan\Analyser\Scope;
1113
use PHPStan\PhpDoc\ResolvedPhpDocBlock;
@@ -171,7 +173,7 @@ private function resolvePhpDoc(Node $node, Scope $scope): ?ResolvedPhpDocBlock
171173
$scope->getFile(),
172174
$scope->getClassReflection() === null ? null : $scope->getClassReflection()->getName(),
173175
$scope->getTraitReflection() === null ? null : $scope->getTraitReflection()->getName(),
174-
$scope->getFunctionName(),
176+
$this->getFunctionName($node),
175177
$docComment->getText(),
176178
);
177179
}
@@ -219,4 +221,13 @@ private function comparePhpDocAndNativeType(?Type $phpDocReturnType, ?Type $nati
219221
return [];
220222
}
221223

224+
private function getFunctionName(Node $node): ?string
225+
{
226+
if ($node instanceof ClassMethod || $node instanceof Function_) {
227+
return $node->name->name;
228+
}
229+
230+
return null;
231+
}
232+
222233
}

tests/Rule/data/ForbidPhpDocNullabilityMismatchWithNativeTypehintRule/code.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,24 @@ public function testConditionTypeForParameter(?float $originalMoney): ?float
8585
return $originalMoney;
8686
}
8787

88+
/**
89+
* @template T as string|null
90+
* @phpstan-param T $stringOrNullInTemplate
91+
* @phpstan-return T
92+
*/
93+
public static function getStringOrNull($stringOrNullInTemplate): ?string
94+
{
95+
return $stringOrNullInTemplate;
96+
}
97+
98+
/**
99+
* @template T as string
100+
* @phpstan-param T $stringOrNullInTemplate
101+
* @phpstan-return T
102+
*/
103+
public static function getStringMissingNull($stringOrNullInTemplate): ?string // error: The @return phpdoc does not contain null, but native return type does
104+
{
105+
return $stringOrNullInTemplate;
106+
}
107+
88108
}

0 commit comments

Comments
 (0)