Skip to content

ForbidVariableTypeOverwriting: relax allowed narrowing and generalization #295

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 4 additions & 4 deletions src/Rule/ForbidVariableTypeOverwritingRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,10 @@ public function processNode(Node $node, Scope $scope): array
return [];
}

if (
!$previousVariableType->isSuperTypeOf($newVariableType)->yes() // allow narrowing
&& !$newVariableType->isSuperTypeOf($previousVariableType)->yes() // allow generalization
) {
$narrowing = $previousVariableType->accepts($newVariableType, true)->yes();
$generalization = $newVariableType->accepts($previousVariableType, true)->yes();

if (!$narrowing && !$generalization) {
$error = RuleErrorBuilder::message("Overwriting variable \$$variableName while changing its type from {$previousVariableType->describe(VerbosityLevel::precise())} to {$newVariableType->describe(VerbosityLevel::precise())}")
->identifier('shipmonk.variableTypeOverwritten')
->build();
Expand Down
8 changes: 8 additions & 0 deletions tests/Rule/data/ForbidVariableTypeOverwritingRule/code.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,11 @@ function testEnumCaseChange() {
function testIntToInt(int $positive, int $negative) {
$positive = $negative;
}

function testFloatToInt(float $float, int $int) {
$float = $int;
}

function testFIntToFloat(int $int, float $float) {
$int = $float;
}