-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClassConstant.php
More file actions
102 lines (88 loc) · 2.93 KB
/
ClassConstant.php
File metadata and controls
102 lines (88 loc) · 2.93 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
<?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 OpenCodeModeling\CodeAst\Code\ClassConstGenerator;
use OpenCodeModeling\CodeAst\Code\IdentifierGenerator;
use OpenCodeModeling\CodeAst\IdentifiedStatementGenerator;
use OpenCodeModeling\CodeAst\Node\StatementGenerator;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\NodeVisitorAbstract;
final class ClassConstant extends NodeVisitorAbstract
{
/**
* @var IdentifiedStatementGenerator
*/
private $lineGenerator;
public function __construct(IdentifiedStatementGenerator $lineGenerator)
{
$this->lineGenerator = $lineGenerator;
}
public static function fromNode(Node\Stmt\ClassConst $node): self
{
return new self(
new StatementGenerator(
$node->consts[0]->name->name,
$node
)
);
}
public static function forClassConstant(
string $constantName,
$constantValue,
int $flags = ClassConstGenerator::FLAG_PUBLIC
): ClassConstant {
return new self(
new IdentifierGenerator(
$constantName,
new ClassConstGenerator($constantName, $constantValue, $flags)
)
);
}
public function afterTraverse(array $nodes): ?array
{
$newNodes = [];
foreach ($nodes as $node) {
$newNodes[] = $node;
if ($node instanceof Namespace_) {
foreach ($node->stmts as $stmt) {
if ($stmt instanceof Class_) {
if ($this->checkConstantExists($stmt)) {
return null;
}
$stmt->stmts = \array_merge(
$stmt->stmts,
$this->lineGenerator->generate()
);
}
}
} elseif ($node instanceof Class_) {
if ($this->checkConstantExists($node)) {
return null;
}
$node->stmts = \array_merge(
$node->stmts,
$this->lineGenerator->generate()
);
}
}
return $newNodes;
}
private function checkConstantExists(Class_ $node): bool
{
foreach ($node->stmts as $stmt) {
if ($stmt instanceof Node\Stmt\ClassConst
&& $stmt->consts[0]->name->name === $this->lineGenerator->identifier()
) {
return true;
}
}
return false;
}
}