forked from phpstan/phpstan-src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomIntParametersRule.php
79 lines (65 loc) · 1.9 KB
/
RandomIntParametersRule.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php declare(strict_types = 1);
namespace PHPStan\Rules\Functions;
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Php\PhpVersion;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\IntegerRangeType;
use PHPStan\Type\VerbosityLevel;
use function array_values;
use function count;
use function sprintf;
/**
* @implements Rule<Node\Expr\FuncCall>
*/
final class RandomIntParametersRule implements Rule
{
public function __construct(
private ReflectionProvider $reflectionProvider,
private PhpVersion $phpVersion,
private bool $reportMaybes,
)
{
}
public function getNodeType(): string
{
return FuncCall::class;
}
public function processNode(Node $node, Scope $scope): array
{
if (!($node->name instanceof Node\Name)) {
return [];
}
if ($this->reflectionProvider->resolveFunctionName($node->name, $scope) !== 'random_int') {
return [];
}
$args = array_values($node->getArgs());
if (count($args) < 2) {
return [];
}
$minType = $scope->getType($args[0]->value)->toInteger();
$maxType = $scope->getType($args[1]->value)->toInteger();
if (
!$minType instanceof ConstantIntegerType && !$minType instanceof IntegerRangeType
|| !$maxType instanceof ConstantIntegerType && !$maxType instanceof IntegerRangeType
) {
return [];
}
$isSmaller = $maxType->isSmallerThan($minType, $this->phpVersion);
if ($isSmaller->yes() || $isSmaller->maybe() && $this->reportMaybes) {
$message = 'Parameter #1 $min (%s) of function random_int expects lower number than parameter #2 $max (%s).';
return [
RuleErrorBuilder::message(sprintf(
$message,
$minType->describe(VerbosityLevel::value()),
$maxType->describe(VerbosityLevel::value()),
))->identifier('argument.type')->build(),
];
}
return [];
}
}