-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNamespaceUse.php
More file actions
101 lines (81 loc) · 2.86 KB
/
Copy pathNamespaceUse.php
File metadata and controls
101 lines (81 loc) · 2.86 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
<?php
/**
* @see https://github.com/open-code-modeling/php-code-ast for the canonical source repository
* @copyright https://github.com/open-code-modeling/php-code-ast/blob/master/COPYRIGHT.md
* @license https://github.com/open-code-modeling/php-code-ast/blob/master/LICENSE.md MIT License
*/
declare(strict_types=1);
namespace OpenCodeModeling\CodeAst\NodeVisitor;
use PhpParser\BuilderFactory;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\NodeVisitorAbstract;
final class NamespaceUse extends NodeVisitorAbstract
{
/**
* @var array
*/
private $imports;
/**
* @var BuilderFactory
**/
private $builderFactory;
public function __construct(...$imports)
{
$this->imports = $imports;
$this->builderFactory = new BuilderFactory();
}
public function afterTraverse(array $nodes): ?array
{
$imports = $this->filterImports($nodes);
if (\count($imports) === 0) {
return null;
}
$newNodes = [];
foreach ($nodes as $node) {
$newNodes[] = $node;
if ($node instanceof Stmt\Namespace_) {
$stmts = $node->stmts;
foreach ($imports as $import) {
if (\is_array($import)) {
$useNamespace = $this->builderFactory->use($import[0]);
$useNamespace->as($import[1]);
} else {
$useNamespace = $this->builderFactory->use($import);
}
\array_unshift($stmts, $useNamespace->getNode());
}
$node->stmts = $stmts; // @phpstan-ignore-line
}
}
return $newNodes;
}
private function filterImports(array $nodes): array
{
$imports = $this->imports;
foreach ($nodes as $node) {
if ($node instanceof Namespace_) {
foreach ($node->stmts as $stmt) {
if ($stmt instanceof Stmt\Use_) {
$imports = \array_filter($imports, static function ($import) use ($stmt) {
$name = $import;
if (\is_array($import)) {
$name = $import[0];
}
return $name !== (string) $stmt->uses[0]->name;
});
}
}
} elseif ($node instanceof Stmt\Use_) {
$imports = \array_filter($imports, static function ($import) use ($node) {
$name = $import;
if (\is_array($import)) {
$name = $import[0];
}
return $name === (string) $node->uses[0]->name;
});
}
}
return $imports;
}
}