8000 Do not mutate `$var instanceof ClassName` inside `assert()` function as it's impossible or hard to kill by maks-rafalko · Pull Request #1852 · infection/infection · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Do not mutate $var instanceof ClassName inside assert() function as it's impossible or hard to kill #1852

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

Merged
merged 1 commit into from
May 11, 2023
Merged
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
23 changes: 22 additions & 1 deletion src/Mutator/Boolean/InstanceOf_.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
use Infection\Mutator\GetMutatorName;
use Infection\Mutator\Mutator;
use Infection\Mutator\MutatorCategory;
use Infection\PhpParser\Visitor\ParentConnector;
use PhpParser\Node;

/**
Expand Down Expand Up @@ -80,6 +81,26 @@ public function mutate(Node $node): iterable

public function canMutate(Node $node): bool
{
return $node instanceof Node\Expr\Instanceof_;
if (!$node instanceof Node\Expr\Instanceof_) {
return false;
}

if ($this->isArgumentOfAssertFunction($node)) {
return false;
}

return true;
}

private function isArgumentOfAssertFunction(Node\Expr\Instanceof_ $node): bool
{
$parentNode = ParentConnector::findParent($node);
$grandParentNode = $parentNode !== null ? ParentConnector::findParent($parentNode) : null;

if (!$grandParentNode instanceof Node\Expr\FuncCall || !$grandParentNode->name instanceof Node\Name) {
return false;
}

return $grandParentNode->name->toLowerString() === 'assert';
}
}
41 changes: 41 additions & 0 deletions tests/phpunit/Mutator/Boolean/InstanceOf_Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,5 +96,46 @@ public function mutationsProvider(): iterable
,
],
];

yield 'It does not mutate an instanceof comparison inside `assert()` function call with a class literal' => [
<<<'PHP'
<?php

return assert($example instanceof Example);
PHP
,
];

yield 'It does not mutate an instanceof comparison inside `assert()` function call with variable' => [
<<<'PHP'
<?php

return assert($example instanceof $foo);
PHP
,
];

yield 'It mutates an instanceof comparison inside other than `assert()` functions' => [
<<<'PHP'
<?php

return someFunc($example instanceof $foo);
PHP
,
[
<<<'PHP'
<?php

return someFunc(true);
PHP
,
<<<'PHP'
<?php

return someFunc(false);
PHP
,
],
];
}
}
0