Skip to content

Commit

Permalink
Multiplication mutator should not mutate when return value is integer
Browse files Browse the repository at this point in the history
  • Loading branch information
sidz authored and maks-rafalko committed May 5, 2021
1 parent bf27a84 commit 0840e69
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
23 changes: 22 additions & 1 deletion src/Mutator/Arithmetic/Multiplication.php
Expand Up @@ -39,6 +39,9 @@
use Infection\Mutator\GetMutatorName;
use Infection\Mutator\Mutator;
use Infection\Mutator\MutatorCategory;
use Infection\PhpParser\Visitor\ParentConnector;
use Infection\PhpParser\Visitor\ReflectionVisitor;
use function is_string;
use PhpParser\Node;

/**
Expand Down Expand Up @@ -94,7 +97,25 @@ public function canMutate(Node $node): bool
return false;
}

return true;
$functionScope = $node->getAttribute(ReflectionVisitor::FUNCTION_SCOPE_KEY);

if (!$functionScope instanceof Node\Stmt\ClassMethod) {
return true;
}

$parentNode = ParentConnector::getParent($node);

if (!$parentNode instanceof Node\Stmt\Return_) {
return true;
}

$returnType = $functionScope->getReturnType();

if ($returnType instanceof Node\Identifier) {
$returnType = $returnType->name;
}

return !(is_string($returnType) && $returnType === 'int');
}

private function isNumericOne(Node $node): bool
Expand Down
42 changes: 42 additions & 0 deletions tests/phpunit/Mutator/Arithmetic/MultiplicationTest.php
Expand Up @@ -135,6 +135,48 @@ public function mutationsProvider(): iterable
<?php
$a = $b * -1.0;
PHP
];

yield 'It does not mutate when class method returns type is integer' => [
<<<'PHP'
<?php
new class
{
public function mul(int $a, int $b): int
{
return $a * $b;
}
};
PHP
];

yield 'It mutates when class method returns type is integer' => [
<<<'PHP'
<?php
new class
{
public function mul(int $a, int $b): int
{
$c = $a * $b;
return 1;
}
};
PHP,
<<<'PHP'
<?php
new class
{
public function mul(int $a, int $b) : int
{
$c = $a / $b;
return 1;
}
};
PHP
];
}
Expand Down

0 comments on commit 0840e69

Please sign in to comment.