rector/rules/code-quality/src/Rector/If_/SimplifyIfNotNullReturnRector.php

100 lines
2.4 KiB
PHP
Raw Normal View History

2019-10-13 05:59:52 +00:00
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\Rector\If_;
use PhpParser\Node;
use PhpParser\Node\Stmt\If_;
use PhpParser\Node\Stmt\Return_;
use Rector\Core\PhpParser\Node\Manipulator\IfManipulator;
use Rector\Core\Rector\AbstractRector;
use Rector\Core\RectorDefinition\CodeSample;
use Rector\Core\RectorDefinition\RectorDefinition;
use Rector\NodeTypeResolver\Node\AttributeKey;
2019-09-03 09:11:45 +00:00
/**
* @see \Rector\CodeQuality\Tests\Rector\If_\SimplifyIfNotNullReturnRector\SimplifyIfNotNullReturnRectorTest
*/
final class SimplifyIfNotNullReturnRector extends AbstractRector
{
/**
* @var IfManipulator
*/
private $ifManipulator;
public function __construct(IfManipulator $ifManipulator)
{
$this->ifManipulator = $ifManipulator;
}
public function getDefinition(): RectorDefinition
{
return new RectorDefinition('Changes redundant null check to instant return', [
new CodeSample(
2019-09-18 06:14:35 +00:00
<<<'PHP'
$newNode = 'something ;
if ($newNode !== null) {
return $newNode;
}
return null;
2019-09-18 06:14:35 +00:00
PHP
,
2019-09-18 06:14:35 +00:00
<<<'PHP'
$newNode = 'something ;
return $newNode;
2019-09-18 06:14:35 +00:00
PHP
),
]);
}
/**
* @return string[]
*/
public function getNodeTypes(): array
{
return [If_::class];
}
/**
* @param If_ $node
*/
public function refactor(Node $node): ?Node
{
$comparedNode = $this->ifManipulator->matchIfNotNullReturnValue($node);
2019-02-17 14:12:47 +00:00
if ($comparedNode !== null) {
$insideIfNode = $node->stmts[0];
$nextNode = $node->getAttribute(AttributeKey::NEXT_NODE);
2019-01-14 18:21:23 +00:00
if (! $nextNode instanceof Return_ || $nextNode->expr === null) {
return null;
}
if (! $this->isNull($nextNode->expr)) {
return null;
}
$this->removeNode($nextNode);
return $insideIfNode;
}
$comparedNode = $this->ifManipulator->matchIfValueReturnValue($node);
2019-02-17 14:12:47 +00:00
if ($comparedNode !== null) {
$nextNode = $node->getAttribute(AttributeKey::NEXT_NODE);
if (! $nextNode instanceof Return_) {
return null;
}
if (! $this->areNodesEqual($comparedNode, $nextNode->expr)) {
return null;
}
$this->removeNode($nextNode);
return clone $nextNode;
}
return null;
}
}