-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProperty.php
More file actions
83 lines (70 loc) · 2.35 KB
/
Copy pathProperty.php
File metadata and controls
83 lines (70 loc) · 2.35 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
<?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\PropertyGenerator;
use PhpParser\Node;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\NodeVisitorAbstract;
final class Property extends NodeVisitorAbstract
{
/**
* @var PropertyGenerator
**/
private $propertyGenerator;
public function __construct(PropertyGenerator $propertyGenerator)
{
$this->propertyGenerator = $propertyGenerator;
}
public static function forClassProperty(
string $name = null,
string $type = null,
$defaultValue = null,
bool $typed = false,
int $flags = PropertyGenerator::FLAG_PRIVATE
): self {
return new self(
new PropertyGenerator($name, $type, $defaultValue, $typed, $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 Stmt\Class_) {
if ($this->checkPropertyExists($stmt)) {
return null;
}
$stmt->stmts[] = $this->propertyGenerator->generate();
}
}
} elseif ($node instanceof Stmt\Class_) {
if ($this->checkPropertyExists($node)) {
return null;
}
$node->stmts[] = $this->propertyGenerator->generate();
}
}
return $newNodes;
}
private function checkPropertyExists(Class_ $node): bool
{
foreach ($node->stmts as $stmt) {
if ($stmt instanceof Node\Stmt\Property
&& $stmt->props[0]->name->name === $this->propertyGenerator->getName()
) {
return true;
}
}
return false;
}
}