-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClassFile.php
More file actions
67 lines (54 loc) · 1.75 KB
/
ClassFile.php
File metadata and controls
67 lines (54 loc) · 1.75 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
<?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\ClassGenerator;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\NodeVisitorAbstract;
class ClassFile extends NodeVisitorAbstract
{
/**
* @var bool
*/
private $classExists = false;
/**
* @var ClassGenerator
**/
private $classGenerator;
public function __construct(ClassGenerator $classGenerator)
{
$this->classGenerator = $classGenerator;
}
public static function fromNode(Class_ $node): self
{
return new self(new ClassGenerator($node->name->name));
}
public function beforeTraverse(array $nodes)
{
foreach ($nodes as $node) {
if ($node instanceof Namespace_) {
foreach ($node->stmts as $stmt) {
if ($stmt instanceof Class_) {
$this->classExists = $stmt->name->name === $this->classGenerator->getName();
}
}
} elseif ($node instanceof Class_) {
$this->classExists = $node->name->name === $this->classGenerator->getName();
}
}
return null;
}
public function afterTraverse(array $nodes): ?array
{
if ($this->classExists === false) {
$nodes[] = $this->classGenerator->generate();
return $nodes;
}
return null;
}
}