rector/rules/DeadCode/Rector/ClassMethod/RemoveDeadConstructorRector.php
Tomas Votruba b5290c94c5 Updated Rector to commit 2d22795af1
2d22795af1 [DeadCode] Skip RemoveDeadConstructorRector on empty constructor with class extends (#611)
2021-08-07 11:33:39 +00:00

88 lines
2.7 KiB
PHP

<?php
declare (strict_types=1);
namespace Rector\DeadCode\Rector\ClassMethod;
use PhpParser\Node;
use PhpParser\Node\Name\FullyQualified;
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 \Rector\Core\Rector\AbstractRector
{
/**
* @var \Rector\Core\NodeManipulator\ClassMethodManipulator
*/
private $classMethodManipulator;
public function __construct(\Rector\Core\NodeManipulator\ClassMethodManipulator $classMethodManipulator)
{
$this->classMethodManipulator = $classMethodManipulator;
}
public function getRuleDefinition() : \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
{
return new \Symplify\RuleDocGenerator\ValueObject\RuleDefinition('Remove empty constructor', [new \Symplify\RuleDocGenerator\ValueObject\CodeSample\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 [\PhpParser\Node\Stmt\ClassMethod::class];
}
/**
* @param ClassMethod $node
*/
public function refactor(\PhpParser\Node $node) : ?\PhpParser\Node
{
$classLike = $node->getAttribute(\Rector\NodeTypeResolver\Node\AttributeKey::CLASS_NODE);
if (!$classLike instanceof \PhpParser\Node\Stmt\Class_) {
return null;
}
if ($this->shouldSkipPropertyPromotion($node)) {
return null;
}
if ($classLike->extends instanceof \PhpParser\Node\Name\FullyQualified) {
return null;
}
$this->removeNode($node);
return null;
}
private function shouldSkipPropertyPromotion(\PhpParser\Node\Stmt\ClassMethod $classMethod) : bool
{
if (!$this->isName($classMethod, \Rector\Core\ValueObject\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);
}
}