forked from rectorphp/rector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRemoveDeadConstructorRector.php
99 lines (85 loc) · 2.34 KB
/
RemoveDeadConstructorRector.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
declare(strict_types=1);
namespace Rector\DeadCode\Rector\ClassMethod;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use Rector\Core\NodeManipulator\ClassMethodManipulator;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\ValueObject\MethodName;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see \Rector\Tests\DeadCode\Rector\ClassMethod\RemoveDeadConstructorRector\RemoveDeadConstructorRectorTest
*/
final class RemoveDeadConstructorRector extends AbstractRector
{
/**
* @var ClassMethodManipulator
*/
private $classMethodManipulator;
public function __construct(ClassMethodManipulator $classMethodManipulator)
{
$this->classMethodManipulator = $classMethodManipulator;
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Remove empty constructor', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
public function __construct()
{
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeClass
{
}
CODE_SAMPLE
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [ClassMethod::class];
}
/**
* @param ClassMethod $node
*/
public function refactor(Node $node): ?Node
{
$classLike = $node->getAttribute(AttributeKey::CLASS_NODE);
if (! $classLike instanceof Class_) {
return null;
}
if ($this->shouldSkipPropertyPromotion($node)) {
return null;
}
$this->removeNode($node);
return null;
}
private function shouldSkipPropertyPromotion(ClassMethod $classMethod): bool
{
if (! $this->isName($classMethod, MethodName::CONSTRUCT)) {
return true;
}
if ($classMethod->stmts === null) {
return true;
}
if ($classMethod->stmts !== []) {
return true;
}
if ($this->classMethodManipulator->isPropertyPromotion($classMethod)) {
return true;
}
return $this->classMethodManipulator->isNamedConstructor($classMethod);
}
}