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