Skip to content

Commit

Permalink
Match expression - report usage of void
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Mar 29, 2021
1 parent 90e49f7 commit 2c0dda3
Show file tree
Hide file tree
Showing 4 changed files with 97 additions and 0 deletions.
1 change: 1 addition & 0 deletions conf/config.level2.neon
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ rules:
- PHPStan\Rules\Cast\InvalidCastRule
- PHPStan\Rules\Cast\InvalidPartOfEncapsedStringRule
- PHPStan\Rules\Cast\PrintRule
- PHPStan\Rules\Comparison\UsageOfVoidMatchExpressionRule
- PHPStan\Rules\Functions\IncompatibleDefaultParameterTypeRule
- PHPStan\Rules\Generics\ClassAncestorsRule
- PHPStan\Rules\Generics\ClassTemplateTypeRule
Expand Down
35 changes: 35 additions & 0 deletions src/Rules/Comparison/UsageOfVoidMatchExpressionRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Comparison;

use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\VoidType;

/**
* @implements Rule<Node\Expr\Match_>
*/
class UsageOfVoidMatchExpressionRule implements Rule
{

public function getNodeType(): string
{
return Node\Expr\Match_::class;
}

public function processNode(Node $node, Scope $scope): array
{
$matchResultType = $scope->getType($node);
if (
$matchResultType instanceof VoidType
&& !$scope->isInFirstLevelStatement()
) {
return [RuleErrorBuilder::message('Result of match expression (void) is used.')->build()];
}

return [];
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php declare(strict_types = 1);

namespace PHPStan\Rules\Comparison;

use PHPStan\Rules\Rule;
use PHPStan\Testing\RuleTestCase;

/**
* @extends RuleTestCase<UsageOfVoidMatchExpressionRule>
*/
class UsageOfVoidMatchExpressionRuleTest extends RuleTestCase
{

protected function getRule(): Rule
{
return new UsageOfVoidMatchExpressionRule();
}

public function testRule(): void
{
if (PHP_VERSION_ID < 80000 && !self::$useStaticReflectionProvider) {
$this->markTestSkipped('Test requires PHP 8.0.');
}

$this->analyse([__DIR__ . '/data/void-match.php'], [
[
'Result of match expression (void) is used.',
21,
],
]);
}

}
28 changes: 28 additions & 0 deletions tests/PHPStan/Rules/Comparison/data/void-match.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php // lint >= 8.0

namespace VoidMatch;

class Foo
{

public function doFoo(): void
{

}

public function doBar(int $i): void
{
match ($i) {
1 => $this->doFoo(),
2 => $this->doFoo(),
default => $this->doFoo(),
};

$a = match ($i) {
1 => $this->doFoo(),
2 => $this->doFoo(),
default => $this->doFoo(),
};
}

}

0 comments on commit 2c0dda3

Please sign in to comment.