-
-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathRectorNodeTraverser.php
More file actions
104 lines (86 loc) · 2.81 KB
/
RectorNodeTraverser.php
File metadata and controls
104 lines (86 loc) · 2.81 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
<?php
declare(strict_types=1);
namespace Rector\PhpParser\NodeTraverser;
use PhpParser\Node;
use PhpParser\Node\Stmt;
use PhpParser\NodeVisitor;
use Rector\Configuration\ConfigurationRuleFilter;
use Rector\Contract\Rector\RectorInterface;
use Rector\VersionBonding\PhpVersionedFilter;
/**
* @see \Rector\Tests\PhpParser\NodeTraverser\RectorNodeTraverserTest
*/
final class RectorNodeTraverser extends AbstractImmutableNodeTraverser
{
private bool $areNodeVisitorsPrepared = false;
/**
* @var array<class-string<Node>, NodeVisitor[]>
*/
private array $visitorsPerNodeClass = [];
/**
* @param RectorInterface[] $rectors
*/
public function __construct(
private array $rectors,
private readonly PhpVersionedFilter $phpVersionedFilter,
private readonly ConfigurationRuleFilter $configurationRuleFilter,
) {
parent::__construct();
}
/**
* @param Stmt[] $nodes
* @return Stmt[]
*/
public function traverse(array $nodes): array
{
$this->prepareNodeVisitors();
return parent::traverse($nodes);
}
/**
* @param RectorInterface[] $rectors
* @api used in tests to update the active rules
*/
public function refreshPhpRectors(array $rectors): void
{
$this->rectors = $rectors;
$this->visitors = [];
$this->visitorsPerNodeClass = [];
$this->areNodeVisitorsPrepared = false;
}
/**
* @return NodeVisitor[]
*/
public function getVisitorsForNode(Node $node): array
{
$nodeClass = $node::class;
if (! isset($this->visitorsPerNodeClass[$nodeClass])) {
$this->visitorsPerNodeClass[$nodeClass] = [];
/** @var RectorInterface $visitor */
foreach ($this->visitors as $visitor) {
foreach ($visitor->getNodeTypes() as $nodeType) {
if (is_a($nodeClass, $nodeType, true)) {
$this->visitorsPerNodeClass[$nodeClass][] = $visitor;
continue 2;
}
}
}
}
return $this->visitorsPerNodeClass[$nodeClass];
}
/**
* This must happen after $this->configuration is set after ProcessCommand::execute() is run, otherwise we get default false positives.
*
* This should be removed after https://github.com/rectorphp/rector/issues/5584 is resolved
*/
private function prepareNodeVisitors(): void
{
if ($this->areNodeVisitorsPrepared) {
return;
}
// filer out by version
$this->visitors = $this->phpVersionedFilter->filter($this->rectors);
// filter by configuration
$this->visitors = $this->configurationRuleFilter->filter($this->visitors);
$this->areNodeVisitorsPrepared = true;
}
}