forked from rectorphp/rector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInlineIfToExplicitIfRector.php
117 lines (102 loc) · 2.86 KB
/
InlineIfToExplicitIfRector.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
declare(strict_types=1);
namespace Rector\CodeQuality\Rector\Expression;
use PhpParser\Node;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\AssignOp;
use PhpParser\Node\Expr\BinaryOp\BooleanAnd;
use PhpParser\Node\Expr\BinaryOp\BooleanOr;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\If_;
use PHPStan\Type\BooleanType;
use Rector\Core\NodeManipulator\BinaryOpManipulator;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* @see https://3v4l.org/dmHCC
*
* @see \Rector\Tests\CodeQuality\Rector\Expression\InlineIfToExplicitIfRector\InlineIfToExplicitIfRectorTest
*/
final class InlineIfToExplicitIfRector extends AbstractRector
{
/**
* @var BinaryOpManipulator
*/
private $binaryOpManipulator;
public function __construct(BinaryOpManipulator $binaryOpManipulator)
{
$this->binaryOpManipulator = $binaryOpManipulator;
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Change inline if to explicit if', [
new CodeSample(
<<<'CODE_SAMPLE'
class SomeClass
{
public function run()
{
$userId = null;
is_null($userId) && $userId = 5;
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class SomeClass
{
public function run()
{
$userId = null;
if (is_null($userId)) {
$userId = 5;
}
}
}
CODE_SAMPLE
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Expression::class];
}
/**
* @param Expression $node
*/
public function refactor(Node $node): ?Node
{
if ($node->expr instanceof BooleanAnd) {
return $this->processExplicitIf($node);
}
if ($node->expr instanceof BooleanOr) {
return $this->processExplicitIf($node);
}
return null;
}
private function processExplicitIf(Expression $expression): ?Node
{
/** @var BooleanAnd|BooleanOr $booleanExpr */
$booleanExpr = $expression->expr;
$leftStaticType = $this->getStaticType($booleanExpr->left);
if (! $leftStaticType instanceof BooleanType) {
return null;
}
if (! $booleanExpr->right instanceof Assign && ! $booleanExpr->right instanceof AssignOp) {
return null;
}
/** @var Expr $expr */
$expr = $booleanExpr instanceof BooleanAnd
? $booleanExpr->left
: $this->binaryOpManipulator->inverseNode($booleanExpr->left);
$if = new If_($expr);
$if->stmts[] = new Expression($booleanExpr->right);
$this->mirrorComments($if, $expression);
return $if;
}
}