Skip to content

Commit 9b000a5

Browse files
claudeondrejmirtes
authored andcommitted
Fix false positive UselessCast for (void) cast on #[\NoDiscard] calls
The PHP 8.5 `(void)` cast exists specifically to discard a value and silence `#[\NoDiscard]` warnings; it is never useless by definition. phpstan/phpstan#14565
1 parent eceb998 commit 9b000a5

3 files changed

Lines changed: 29 additions & 0 deletions

File tree

src/Rules/Cast/UselessCastRule.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use PhpParser\Node;
66
use PhpParser\Node\Expr\Cast;
7+
use PhpParser\Node\Expr\Cast\Void_;
78
use PHPStan\Analyser\Scope;
89
use PHPStan\Rules\Rule;
910
use PHPStan\Rules\RuleErrorBuilder;
@@ -38,6 +39,10 @@ public function getNodeType(): string
3839

3940
public function processNode(Node $node, Scope $scope): array
4041
{
42+
if ($node instanceof Void_) {
43+
return [];
44+
}
45+
4146
$castType = $scope->getType($node);
4247
if ($castType instanceof ErrorType) {
4348
return [];

tests/Rules/Cast/UselessCastRuleTest.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,4 +89,10 @@ public function testReportPhpDoc(): void
8989
]);
9090
}
9191

92+
public function testBug14565(): void
93+
{
94+
$this->treatPhpDocTypesAsCertain = true;
95+
$this->analyse([__DIR__ . '/data/bug-14565.php'], []);
96+
}
97+
9298
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php // lint >= 8.5
2+
3+
namespace Bug14565;
4+
5+
class Foo
6+
{
7+
8+
#[\NoDiscard]
9+
public function bar(): int
10+
{
11+
return 1;
12+
}
13+
14+
}
15+
16+
function (Foo $foo): void {
17+
(void) $foo->bar();
18+
};

0 commit comments

Comments
 (0)