Repository navigation
Expand file tree
/
Copy pathReplaceBlockToItsStmtsRector.php
More file actions
90 lines (79 loc) · 2.03 KB
/
Copy pathReplaceBlockToItsStmtsRector.php
File metadata and controls
90 lines (79 loc) · 2.03 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
<?php
declare(strict_types=1);
namespace Rector\DeadCode\Rector\Block;
use PhpParser\Node;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Block;
use PhpParser\NodeVisitor;
use Rector\Rector\AbstractRector;
use Rector\RuleDoc\CodeSample\CodeSample;
use Rector\RuleDoc\RuleDefinition;
/**
* @see \Rector\Tests\DeadCode\Rector\Block\ReplaceBlockToItsStmtsRector\ReplaceBlockToItsStmtsRectorTest
* @see https://3v4l.org/ZUfEV
*/
final class ReplaceBlockToItsStmtsRector extends AbstractRector
{
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Replace Block Stmt with its stmts',
[
new CodeSample(
<<<'CODE_SAMPLE'
{
echo "statement 1";
echo PHP_EOL;
echo "statement 2";
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
echo "statement 1";
echo PHP_EOL;
echo "statement 2";
CODE_SAMPLE
),
]
);
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Block::class];
}
/**
* @param Block $node
* @return int|Stmt[]
*/
public function refactor(Node $node): int|array
{
if ($node->stmts === []) {
return NodeVisitor::REMOVE_NODE;
}
$stmts = $this->flattenBlocks($node->stmts);
if ($stmts === []) {
return NodeVisitor::REMOVE_NODE;
}
return $stmts;
}
/**
* Flatten nested blocks and drop empty ones in the same pass, as replaced stmts are not re-traversed
* @param Stmt[] $stmts
* @return Stmt[]
*/
private function flattenBlocks(array $stmts): array
{
$flattenedStmts = [];
foreach ($stmts as $stmt) {
if ($stmt instanceof Block) {
$flattenedStmts = [...$flattenedStmts, ...$this->flattenBlocks($stmt->stmts)];
continue;
}
$flattenedStmts[] = $stmt;
}
return $flattenedStmts;
}
}