mirror of
https://github.com/rectorphp/rector.git
synced 2024-06-14 07:02:24 +00:00
7e7a2f067a
476cfb00cb
disable fallback for now
79 lines
2.2 KiB
PHP
79 lines
2.2 KiB
PHP
<?php
|
|
|
|
declare (strict_types=1);
|
|
namespace Rector\CodeQuality\Rector\Expression;
|
|
|
|
use PhpParser\Node;
|
|
use PhpParser\Node\Expr;
|
|
use PhpParser\Node\Expr\Ternary;
|
|
use PhpParser\Node\Stmt\Expression;
|
|
use PhpParser\Node\Stmt\If_;
|
|
use PHPStan\Analyser\Scope;
|
|
use Rector\DeadCode\SideEffect\SideEffectNodeDetector;
|
|
use Rector\Rector\AbstractScopeAwareRector;
|
|
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
|
|
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
|
|
/**
|
|
* @see \Rector\Tests\CodeQuality\Rector\Expression\TernaryFalseExpressionToIfRector\TernaryFalseExpressionToIfRectorTest
|
|
*/
|
|
final class TernaryFalseExpressionToIfRector extends AbstractScopeAwareRector
|
|
{
|
|
/**
|
|
* @readonly
|
|
* @var \Rector\DeadCode\SideEffect\SideEffectNodeDetector
|
|
*/
|
|
private $sideEffectNodeDetector;
|
|
public function __construct(SideEffectNodeDetector $sideEffectNodeDetector)
|
|
{
|
|
$this->sideEffectNodeDetector = $sideEffectNodeDetector;
|
|
}
|
|
public function getRuleDefinition() : RuleDefinition
|
|
{
|
|
return new RuleDefinition('Change ternary with false to if and explicit call', [new CodeSample(<<<'CODE_SAMPLE'
|
|
final class SomeClass
|
|
{
|
|
public function run($value, $someMethod)
|
|
{
|
|
$value ? $someMethod->call($value) : false;
|
|
}
|
|
}
|
|
CODE_SAMPLE
|
|
, <<<'CODE_SAMPLE'
|
|
final class SomeClass
|
|
{
|
|
public function run($value, $someMethod)
|
|
{
|
|
if ($value) {
|
|
$someMethod->call($value);
|
|
}
|
|
}
|
|
}
|
|
CODE_SAMPLE
|
|
)]);
|
|
}
|
|
/**
|
|
* @return array<class-string<Node>>
|
|
*/
|
|
public function getNodeTypes() : array
|
|
{
|
|
return [Expression::class];
|
|
}
|
|
/**
|
|
* @param Expression $node
|
|
*/
|
|
public function refactorWithScope(Node $node, Scope $scope) : ?Node
|
|
{
|
|
if (!$node->expr instanceof Ternary) {
|
|
return null;
|
|
}
|
|
$ternary = $node->expr;
|
|
if (!$ternary->if instanceof Expr) {
|
|
return null;
|
|
}
|
|
if ($this->sideEffectNodeDetector->detect($ternary->else, $scope) || $this->sideEffectNodeDetector->detectCallExpr($ternary->else, $scope)) {
|
|
return null;
|
|
}
|
|
return new If_($ternary->cond, ['stmts' => [new Expression($ternary->if)]]);
|
|
}
|
|
}
|