Skip to content

Commit 4518c50

Browse files
authored
[DeadCode] Allow remove createMock method call on RemoveUnusedVariableAssignRector (#6951)
* [DeadCode] Allow remove common create mock method calls on tests * only createMock
1 parent a063538 commit 4518c50

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?php
2+
3+
namespace Rector\Tests\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector\Fixture;
4+
5+
use PHPUnit\Framework\TestCase;
6+
7+
final class CreateMockInTest extends TestCase
8+
{
9+
public function test($params)
10+
{
11+
$tmp = $this->createMock('SomeClass');
12+
}
13+
}
14+
15+
?>
16+
-----
17+
<?php
18+
19+
namespace Rector\Tests\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector\Fixture;
20+
21+
use PHPUnit\Framework\TestCase;
22+
23+
final class CreateMockInTest extends TestCase
24+
{
25+
public function test($params)
26+
{
27+
}
28+
}
29+
30+
?>

rules/DeadCode/SideEffect/SideEffectNodeDetector.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
use PhpParser\Node\Name;
1919
use PhpParser\Node\Name\FullyQualified;
2020
use PHPStan\Type\ObjectType;
21+
use Rector\NodeNameResolver\NodeNameResolver;
22+
use Rector\NodeTypeResolver\NodeTypeResolver;
2123
use Rector\PhpParser\Node\BetterNodeFinder;
2224

2325
final readonly class SideEffectNodeDetector
@@ -35,6 +37,8 @@
3537
public function __construct(
3638
private PureFunctionDetector $pureFunctionDetector,
3739
private BetterNodeFinder $betterNodeFinder,
40+
private NodeTypeResolver $nodeTypeResolver,
41+
private NodeNameResolver $nodeNameResolver
3842
) {
3943
}
4044

@@ -64,6 +68,10 @@ public function detectCallExpr(Node $node): bool
6468
return false;
6569
}
6670

71+
if (($node instanceof MethodCall || $node instanceof StaticCall) && $this->isTestMock($node)) {
72+
return false;
73+
}
74+
6775
$exprClass = $node::class;
6876
if (in_array($exprClass, self::CALL_EXPR_SIDE_EFFECT_NODE_TYPES, true)) {
6977
return true;
@@ -82,6 +90,18 @@ public function detectCallExpr(Node $node): bool
8290
return false;
8391
}
8492

93+
private function isTestMock(MethodCall|StaticCall $node): bool
94+
{
95+
$objectType = new ObjectType('PHPUnit\Framework\TestCase');
96+
$nodeCaller = $node instanceof MethodCall ? $node->var : $node->class;
97+
98+
if (! $this->nodeTypeResolver->isObjectType($nodeCaller, $objectType)) {
99+
return false;
100+
}
101+
102+
return $this->nodeNameResolver->isName($node->name, 'createMock');
103+
}
104+
85105
private function isPhpParser(New_ $new): bool
86106
{
87107
if (! $new->class instanceof FullyQualified) {

0 commit comments

Comments
 (0)