Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion src/Rules/Functions/RandomIntParametersRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use PHPStan\Type\IntegerRangeType;
use PHPStan\Type\VerbosityLevel;
use function count;
use function is_string;
use function sprintf;

/**
Expand Down Expand Up @@ -65,7 +66,7 @@ public function processNode(Node $node, Scope $scope): array

$isSmaller = $maxType->isSmallerThan($minType, $this->phpVersion);

if ($isSmaller->yes() || $isSmaller->maybe() && $this->reportMaybes) {
if ($isSmaller->yes() || $isSmaller->maybe() && $this->reportMaybes && !$this->sharesVariable($args[0]->value, $args[1]->value)) {
$message = 'Parameter #1 $min (%s) of function random_int expects lower number than parameter #2 $max (%s).';
return [
RuleErrorBuilder::message(sprintf(
Expand All @@ -79,4 +80,46 @@ public function processNode(Node $node, Scope $scope): array
return [];
}

private function sharesVariable(Node\Expr $expr1, Node\Expr $expr2): bool
{
$vars1 = $this->extractVariableNames($expr1);
if ($vars1 === []) {
return false;
}

$vars2 = $this->extractVariableNames($expr2);

foreach ($vars1 as $var => $_) {
if (isset($vars2[$var])) {
return true;
}
}

return false;
}

/**
* @return array<string, true>
*/
private function extractVariableNames(Node\Expr $expr): array
{
$vars = [];
if ($expr instanceof Node\Expr\Variable && is_string($expr->name)) {
$vars[$expr->name] = true;
}

foreach ($expr->getSubNodeNames() as $name) {
$subNode = $expr->{$name};
if (!($subNode instanceof Node\Expr)) {
continue;
}

foreach ($this->extractVariableNames($subNode) as $var => $_) {
$vars[$var] = true;
}
}

return $vars;
}

}
5 changes: 5 additions & 0 deletions tests/PHPStan/Rules/Functions/RandomIntParametersRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,9 @@ public function testBug6361(): void
$this->analyse([__DIR__ . '/data/bug-6361.php'], []);
}

public function testBug13092(): void
{
$this->analyse([__DIR__ . '/data/bug-13092.php'], []);
}

}
12 changes: 12 additions & 0 deletions tests/PHPStan/Rules/Functions/data/bug-13092.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php declare(strict_types = 1);

namespace Bug13092;

class HelloWorld
{
public function sayHello(): void
{
$shoppers = \random_int(1000, 10000);
$transactions = \random_int($shoppers, $shoppers * 3);
}
}
Loading