rector/packages/dead-code/src/Rector/Stmt/RemoveDeadStmtRector.php

96 lines
2.2 KiB
PHP
Raw Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare(strict_types=1);
2018-12-25 11:38:07 +00:00
namespace Rector\DeadCode\Rector\Stmt;
use PhpParser\Node;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Nop;
2020-02-02 18:15:36 +00:00
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\RectorDefinition\CodeSample;
use Rector\Core\RectorDefinition\RectorDefinition;
2020-02-02 18:15:36 +00:00
use Rector\NodeTypeResolver\Node\AttributeKey;
2019-09-03 09:11:45 +00:00
/**
* @see \Rector\DeadCode\Tests\Rector\Stmt\RemoveDeadStmtRector\RemoveDeadStmtRectorTest
*/
2018-12-25 11:38:07 +00:00
final class RemoveDeadStmtRector extends AbstractRector
{
2020-02-02 18:15:36 +00:00
/**
* @var PhpDocInfoFactory
*/
private $phpDocInfoFactory;
public function __construct(PhpDocInfoFactory $phpDocInfoFactory)
{
$this->phpDocInfoFactory = $phpDocInfoFactory;
}
public function getDefinition(): RectorDefinition
{
2018-12-25 11:38:07 +00:00
return new RectorDefinition('Removes dead code statements', [
new CodeSample(
2019-09-18 06:14:35 +00:00
<<<'PHP'
$value = 5;
$value;
2019-09-18 06:14:35 +00:00
PHP
,
2019-09-18 06:14:35 +00:00
<<<'PHP'
$value = 5;
2019-09-18 06:14:35 +00:00
PHP
),
]);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [Expression::class];
}
2020-02-02 18:15:36 +00:00
/**
* @param Expression $node
*/
public function refactor(Node $node): ?Node
{
$livingCode = $this->keepLivingCodeFromExpr($node->expr);
if ($livingCode === []) {
2020-02-02 18:15:36 +00:00
return $this->removeNodeAndKeepComments($node);
}
$firstExpr = array_shift($livingCode);
$node->expr = $firstExpr;
foreach ($livingCode as $expr) {
2020-02-02 18:15:36 +00:00
$newNode = new Expression($expr);
$this->addNodeAfterNode($newNode, $node);
}
return null;
}
2020-02-02 18:15:36 +00:00
private function removeNodeAndKeepComments(Node $node): ?Node
{
2020-02-02 18:15:36 +00:00
/** @var PhpDocInfo $phpDocInfo */
$phpDocInfo = $node->getAttribute(AttributeKey::PHP_DOC_INFO);
2019-02-17 14:12:47 +00:00
if ($node->getComments() !== []) {
$nop = new Nop();
2020-02-02 18:15:36 +00:00
$nop->setAttribute(AttributeKey::PHP_DOC_INFO, $phpDocInfo);
$this->phpDocInfoFactory->createFromNode($nop);
return $nop;
}
$this->removeNode($node);
return null;
}
}