forked from phpowermove/php-code-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileParser.php
More file actions
104 lines (83 loc) · 2.3 KB
/
FileParser.php
File metadata and controls
104 lines (83 loc) · 2.3 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 gossi\codegen\parser;
use gossi\codegen\parser\visitor\ParserVisitorInterface;
use phootwork\collection\Set;
use phootwork\file\exception\FileNotFoundException;
use phootwork\file\File;
use PhpParser\Node;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;
use PhpParser\Parser;
class FileParser extends NodeVisitorAbstract {
private $visitors;
private $filename;
public function __construct($filename) {
$this->filename = $filename;
$this->visitors = new Set();
}
public function addVisitor(ParserVisitorInterface $visitor) {
$this->visitors->add($visitor);
return $this;
}
public function removeVisitor(ParserVisitorInterface $visitor) {
$this->visitors->remove($visitor);
return $this;
}
public function hasVisitor(ParserVisitorInterface $visitor): bool {
return $this->visitors->contains($visitor);
}
/**
* @throws FileNotFoundException
*/
public function parse() {
$file = new File($this->filename);
if (!$file->exists()) {
throw new FileNotFoundException(sprintf('File (%s) does not exist.', $this->filename));
}
$parser = $this->getParser();
$traverser = new NodeTraverser();
$traverser->addVisitor($this);
$traverser->traverse($parser->parse($file->read()));
}
private function getParser(): Parser {
$factory = new \PhpParser\ParserFactory();
return $factory->create(\PhpParser\ParserFactory::PREFER_PHP7);
}
public function enterNode(Node $node) {
foreach ($this->visitors as $visitor) {
switch ($node->getType()) {
case 'Stmt_Namespace':
$visitor->visitNamespace($node);
break;
case 'Stmt_UseUse':
$visitor->visitUseStatement($node);
break;
case 'Stmt_Class':
$visitor->visitStruct($node);
$visitor->visitClass($node);
break;
case 'Stmt_Interface':
$visitor->visitStruct($node);
$visitor->visitInterface($node);
break;
case 'Stmt_Trait':
$visitor->visitStruct($node);
$visitor->visitTrait($node);
break;
case 'Stmt_TraitUse':
$visitor->visitTraitUse($node);
break;
case 'Stmt_ClassConst':
$visitor->visitConstants($node);
break;
case 'Stmt_Property':
$visitor->visitProperty($node);
break;
case 'Stmt_ClassMethod':
$visitor->visitMethod($node);
break;
}
}
}
}