Repository navigation
Expand file tree
/
Copy pathAlternativeIfToBracketRector.php
More file actions
105 lines (88 loc) · 2.38 KB
/
Copy pathAlternativeIfToBracketRector.php
File metadata and controls
105 lines (88 loc) · 2.38 KB
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
<?php
declare(strict_types=1);
namespace Rector\CodingStyle\Rector\If_;
use PhpParser\Node;
use PhpParser\Node\Stmt\If_;
use PhpParser\Token;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\Rector\AbstractRector;
use Rector\RuleDoc\CodeSample\CodeSample;
use Rector\RuleDoc\RuleDefinition;
/**
* @see \Rector\Tests\CodingStyle\Rector\If_\AlternativeIfToBracketRector\AlternativeIfToBracketRectorTest
*/
final class AlternativeIfToBracketRector extends AbstractRector
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition('Change alternative if/elseif/else/endif syntax to bracket syntax', [
new CodeSample(
<<<'CODE_SAMPLE'
if ($value) :
$result = 1;
else :
$result = 2;
endif;
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
if ($value) {
$result = 1;
} else {
$result = 2;
}
CODE_SAMPLE
),
]);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [If_::class];
}
/**
* @param If_ $node
*/
public function refactor(Node $node): ?Node
{
if ($this->getFile()->containsHTML()) {
return null;
}
if (! $this->isAlternativeSyntax($node)) {
return null;
}
// force reprint of the whole if/elseif/else chain with bracket syntax
$node->setAttribute(AttributeKey::ORIGINAL_NODE, null);
foreach ($node->elseifs as $elseif) {
$elseif->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
if ($node->else instanceof Node) {
$node->else->setAttribute(AttributeKey::ORIGINAL_NODE, null);
}
return $node;
}
private function isAlternativeSyntax(If_ $if): bool
{
$startTokenPos = $if->cond->getEndTokenPos();
if ($startTokenPos < 0) {
return false;
}
$oldTokens = $this->getFile()
->getOldTokens();
for ($i = $startTokenPos + 1; isset($oldTokens[$i]); ++$i) {
$token = $oldTokens[$i];
if (! $token instanceof Token) {
continue;
}
if ($token->text === ':') {
return true;
}
if ($token->text === '{') {
return false;
}
}
return false;
}
}