Skip to content

Commit ab3c28b

Browse files
New VoidCastRule
1 parent b348995 commit ab3c28b

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

src/Rules/Cast/VoidCastRule.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\Cast;
4+
5+
use PhpParser\Node;
6+
use PHPStan\Analyser\Scope;
7+
use PHPStan\DependencyInjection\RegisteredRule;
8+
use PHPStan\Rules\Rule;
9+
use PHPStan\Rules\RuleErrorBuilder;
10+
11+
/**
12+
* @implements Rule<Node\Expr\Cast\Void_>
13+
*/
14+
#[RegisteredRule(level: 0)]
15+
final class VoidCastRule implements Rule
16+
{
17+
18+
public function __construct()
19+
{
20+
}
21+
22+
public function getNodeType(): string
23+
{
24+
return Node\Expr\Cast\Void_::class;
25+
}
26+
27+
public function processNode(Node $node, Scope $scope): array
28+
{
29+
if ($scope->isInFirstLevelStatement()) {
30+
return [];
31+
}
32+
33+
return [
34+
RuleErrorBuilder::message('The (void) cast cannot be used within an expression.')
35+
->identifier('cast.void')
36+
->nonIgnorable()
37+
->build(),
38+
];
39+
}
40+
41+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\Cast;
4+
5+
use PHPStan\Rules\Rule;
6+
use PHPStan\Testing\RuleTestCase;
7+
8+
/**
9+
* @extends RuleTestCase<VoidCastRule>
10+
*/
11+
class VoidCastRuleTest extends RuleTestCase
12+
{
13+
14+
protected function getRule(): Rule
15+
{
16+
return new VoidCastRule();
17+
}
18+
19+
public function testPrintRule(): void
20+
{
21+
$this->analyse([__DIR__ . '/data/void-cast.php'], [
22+
[
23+
'The (void) cast cannot be used within an expression.',
24+
5,
25+
],
26+
[
27+
'The (void) cast cannot be used within an expression.',
28+
6,
29+
],
30+
[
31+
'The (void) cast cannot be used within an expression.',
32+
7,
33+
],
34+
]);
35+
}
36+
37+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<?php
2+
3+
namespace VoidCast;
4+
5+
$a = (void)$z;
6+
$b = (void)(1 + 1);
7+
var_dump( (void)$c );

0 commit comments

Comments
 (0)