rector/rules/DeadCode/Rector/FunctionLike/RemoveDeadReturnRector.php

81 lines
2.0 KiB
PHP
Raw Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare (strict_types=1);
2022-06-06 16:43:29 +00:00
namespace RectorPrefix20220606\Rector\DeadCode\Rector\FunctionLike;
2019-03-26 11:17:08 +00:00
2022-06-06 16:43:29 +00:00
use RectorPrefix20220606\PhpParser\Node;
use RectorPrefix20220606\PhpParser\Node\Expr\Closure;
use RectorPrefix20220606\PhpParser\Node\Stmt\ClassMethod;
use RectorPrefix20220606\PhpParser\Node\Stmt\Function_;
use RectorPrefix20220606\PhpParser\Node\Stmt\Return_;
use RectorPrefix20220606\Rector\Core\Rector\AbstractRector;
use RectorPrefix20220606\Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use RectorPrefix20220606\Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
2019-09-03 09:11:45 +00:00
/**
* @see \Rector\Tests\DeadCode\Rector\FunctionLike\RemoveDeadReturnRector\RemoveDeadReturnRectorTest
2019-09-03 09:11:45 +00:00
*/
2022-06-06 16:43:29 +00:00
final class RemoveDeadReturnRector extends AbstractRector
2019-03-26 11:17:08 +00:00
{
2022-06-06 16:43:29 +00:00
public function getRuleDefinition() : RuleDefinition
2019-03-26 11:17:08 +00:00
{
2022-06-06 16:43:29 +00:00
return new RuleDefinition('Remove last return in the functions, since does not do anything', [new CodeSample(<<<'CODE_SAMPLE'
2019-03-26 11:17:08 +00:00
class SomeClass
{
public function run()
{
$shallWeDoThis = true;
if ($shallWeDoThis) {
return;
}
return;
}
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
2019-03-26 11:17:08 +00:00
class SomeClass
{
public function run()
{
$shallWeDoThis = true;
if ($shallWeDoThis) {
return;
}
}
}
CODE_SAMPLE
)]);
2019-03-26 11:17:08 +00:00
}
/**
* @return array<class-string<Node>>
2019-03-26 11:17:08 +00:00
*/
public function getNodeTypes() : array
2019-03-26 11:17:08 +00:00
{
2022-06-06 16:43:29 +00:00
return [ClassMethod::class, Function_::class, Closure::class];
2019-03-26 11:17:08 +00:00
}
/**
* @param ClassMethod|Function_|Closure $node
2019-03-26 11:17:08 +00:00
*/
2022-06-06 16:43:29 +00:00
public function refactor(Node $node) : ?Node
2019-03-26 11:17:08 +00:00
{
if ($node->stmts === []) {
return null;
}
if ($node->stmts === null) {
2019-03-26 11:17:08 +00:00
return null;
}
$stmtValues = \array_values($node->stmts);
$lastStmt = \end($stmtValues);
2022-06-06 16:43:29 +00:00
if (!$lastStmt instanceof Return_) {
2019-03-26 11:17:08 +00:00
return null;
}
if ($lastStmt->expr !== null) {
return null;
}
$this->removeNode($lastStmt);
return $node;
}
}