-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathCodeParser.php
More file actions
269 lines (232 loc) · 7.68 KB
/
CodeParser.php
File metadata and controls
269 lines (232 loc) · 7.68 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 2.8.0
* @license https://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Bake\CodeGen;
use PhpParser\Error;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\GroupUse;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\Node\Stmt\Use_;
use PhpParser\Node\UseItem;
use PhpParser\NodeAbstract;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor;
use PhpParser\NodeVisitorAbstract;
use PhpParser\Parser;
use PhpParser\ParserFactory;
use PhpParser\PhpVersion;
/**
* @internal
*/
class CodeParser extends NodeVisitorAbstract
{
/**
* @var string
*/
protected const INDENT = ' ';
/**
* @var \PhpParser\Parser
*/
protected Parser $parser;
/**
* @var \PhpParser\NodeTraverser
*/
protected NodeTraverser $traverser;
/**
* @var string
*/
protected string $fileText = '';
/**
* @var array
*/
protected array $parsed = [];
/**
* Constructor
*/
public function __construct()
{
$version = PhpVersion::fromComponents(8, 1);
$this->parser = (new ParserFactory())->createForVersion($version);
$this->traverser = new NodeTraverser();
$this->traverser->addVisitor($this);
}
/**
* @param string $code Code to parse
* @return \Bake\CodeGen\ParsedFile|null
* @throws \Bake\CodeGen\ParseException
*/
public function parseFile(string $code): ?ParsedFile
{
$this->fileText = $code;
try {
$ast = $this->parser->parse($code);
if ($ast === null) {
return null;
}
$this->traverser->traverse($ast);
} catch (Error $e) {
throw new ParseException($e->getMessage(), null, $e);
}
if (!isset($this->parsed['namespace'], $this->parsed['class'])) {
return null;
}
return new ParsedFile(
$this->parsed['namespace'],
$this->parsed['imports']['class'],
$this->parsed['imports']['function'],
$this->parsed['imports']['const'],
$this->parsed['class'],
);
}
/**
* @inheritDoc
*/
public function beforeTraverse(array $nodes)
{
$this->parsed = [
'imports' => [
'class' => [],
'function' => [],
'const' => [],
],
];
return null;
}
/**
* @inheritDoc
*/
public function enterNode(Node $node)
{
if ($node instanceof Namespace_) {
if (isset($this->parsed['namespace'])) {
throw new ParseException('Multiple namespaces are not not supported, update your file');
}
$this->parsed['namespace'] = (string)$node->name;
return null;
}
if ($node instanceof Use_) {
if (count($node->uses) > 1) {
throw new ParseException('Multiple use statements per line are not supported, update your file');
}
if ($node->uses === []) {
throw new ParseException('Use statement without uses!');
}
[$alias, $target] = $this->normalizeUse($node->uses[0]);
switch ($node->type) {
case Use_::TYPE_NORMAL:
$this->parsed['imports']['class'][$alias] = $target;
break;
case Use_::TYPE_FUNCTION:
$this->parsed['imports']['function'][$alias] = $target;
break;
case Use_::TYPE_CONSTANT:
$this->parsed['imports']['const'][$alias] = $target;
break;
}
return NodeVisitor::DONT_TRAVERSE_CHILDREN;
}
if ($node instanceof GroupUse) {
throw new ParseException('Group use statements are not supported, update your file');
}
if ($node instanceof Class_) {
if (!isset($this->parsed['namespace'])) {
throw new ParseException('Classes defined in the global namespace is not supported, update your file');
}
if (isset($this->parsed['class'])) {
throw new ParseException('Multiple classes are not supported, update your file');
}
$constants = [];
foreach ($node->getConstants() as $constant) {
if (count($constant->consts) > 1) {
throw new ParseException('Multiple constants per line are not supported, update your file');
}
$const = current($constant->consts);
if ($const === false) {
continue;
}
$name = (string)$const->name;
$constants[$name] = $this->getNodeCode($constant);
}
$properties = [];
foreach ($node->getProperties() as $property) {
if (count($property->props) > 1) {
throw new ParseException('Multiple properties per line are not supported, update your file');
}
$prop = current($property->props);
if ($prop === false) {
continue;
}
$name = (string)$prop->name;
$properties[$name] = $this->getNodeCode($property);
}
$methods = [];
foreach ($node->getMethods() as $method) {
$name = (string)$method->name;
$methods[$name] = $this->getNodeCode($method);
}
$implements = array_map(function ($name) {
return (string)$name;
}, $node->implements);
$this->parsed['class'] = new ParsedClass(
(string)$node->name,
$implements,
$constants,
$properties,
$methods,
);
return NodeVisitor::DONT_TRAVERSE_CHILDREN;
}
return null;
}
/**
* @param \PhpParser\NodeAbstract $node Parser node
* @return string
*/
protected function getNodeCode(NodeAbstract $node): string
{
$code = '';
$doc = $node->getDocComment() ? $node->getDocComment()->getText() : '';
if ($doc) {
$code = static::INDENT . $doc . "\n";
}
$startPos = $node->getStartFilePos();
$endPos = $node->getEndFilePos();
$code .= static::INDENT . substr($this->fileText, $startPos, $endPos - $startPos + 1);
return $code;
}
/**
* @param \PhpParser\Node\UseItem $use Use item
* @param string|null $prefix Group use prefix
* @return array{string, string}
*/
protected function normalizeUse(UseItem $use, ?string $prefix = null): array
{
$name = (string)$use->name;
if ($prefix) {
$name = $prefix . '\\' . $name;
}
$alias = $use->alias;
if (!$alias) {
$last = strrpos($name, '\\', -1);
if ($last !== false) {
$alias = substr($name, strrpos($name, '\\', -1) + 1);
} else {
$alias = $name;
}
}
return [(string)$alias, $name];
}
}