From aeb98d0e622bab2b2d892b87cf7d84825d73327a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 2 May 2026 06:48:06 +0000 Subject: [PATCH] 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. https://github.com/phpstan/phpstan/issues/14565 --- src/Rules/Cast/UselessCastRule.php | 5 +++++ tests/Rules/Cast/UselessCastRuleTest.php | 6 ++++++ tests/Rules/Cast/data/bug-14565.php | 18 ++++++++++++++++++ 3 files changed, 29 insertions(+) create mode 100644 tests/Rules/Cast/data/bug-14565.php diff --git a/src/Rules/Cast/UselessCastRule.php b/src/Rules/Cast/UselessCastRule.php index 66297505..4e0be959 100644 --- a/src/Rules/Cast/UselessCastRule.php +++ b/src/Rules/Cast/UselessCastRule.php @@ -4,6 +4,7 @@ use PhpParser\Node; use PhpParser\Node\Expr\Cast; +use PhpParser\Node\Expr\Cast\Void_; use PHPStan\Analyser\Scope; use PHPStan\Rules\Rule; use PHPStan\Rules\RuleErrorBuilder; @@ -38,6 +39,10 @@ public function getNodeType(): string public function processNode(Node $node, Scope $scope): array { + if ($node instanceof Void_) { + return []; + } + $castType = $scope->getType($node); if ($castType instanceof ErrorType) { return []; diff --git a/tests/Rules/Cast/UselessCastRuleTest.php b/tests/Rules/Cast/UselessCastRuleTest.php index 2a56ca64..e0297e84 100644 --- a/tests/Rules/Cast/UselessCastRuleTest.php +++ b/tests/Rules/Cast/UselessCastRuleTest.php @@ -89,4 +89,10 @@ public function testReportPhpDoc(): void ]); } + public function testBug14565(): void + { + $this->treatPhpDocTypesAsCertain = true; + $this->analyse([__DIR__ . '/data/bug-14565.php'], []); + } + } diff --git a/tests/Rules/Cast/data/bug-14565.php b/tests/Rules/Cast/data/bug-14565.php new file mode 100644 index 00000000..bb6b0635 --- /dev/null +++ b/tests/Rules/Cast/data/bug-14565.php @@ -0,0 +1,18 @@ += 8.5 + +namespace Bug14565; + +class Foo +{ + + #[\NoDiscard] + public function bar(): int + { + return 1; + } + +} + +function (Foo $foo): void { + (void) $foo->bar(); +};