Repository navigation
Expand file tree
/
Copy pathPhpParser.php
More file actions
240 lines (207 loc) · 7.65 KB
/
Copy pathPhpParser.php
File metadata and controls
240 lines (207 loc) · 7.65 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
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\CodeParser;
use Hyperf\CodeParser\Exception\InvalidArgumentException;
use Hyperf\Collection\Arr;
use PhpParser\Node;
use PhpParser\Parser;
use PhpParser\ParserFactory;
use ReflectionClass;
use ReflectionException;
use ReflectionNamedType;
use ReflectionParameter;
use ReflectionType;
use ReflectionUnionType;
use function Hyperf\Support\value;
class PhpParser
{
public const TYPES = [
'int',
'float',
'string',
'bool',
'array',
'object',
'resource',
'mixed',
'null',
];
protected static ?PhpParser $instance = null;
protected Parser $parser;
public function __construct()
{
$parserFactory = new ParserFactory();
$this->parser = $parserFactory->createForNewestSupportedVersion();
}
public static function getInstance(): PhpParser
{
if (static::$instance) {
return static::$instance;
}
return static::$instance = new static();
}
/**
* @return null|Node\Stmt[]
*/
public function getNodesFromReflectionClass(ReflectionClass $reflectionClass): ?array
{
$code = file_get_contents($reflectionClass->getFileName());
return $this->parser->parse($code);
}
public function getNodeFromReflectionType(ReflectionType $reflection): Node
{
if ($reflection instanceof ReflectionUnionType) {
$unionType = [];
foreach ($reflection->getTypes() as $objType) {
$type = $objType->getName();
if (! in_array($type, static::TYPES)) {
$unionType[] = new Node\Name('\\' . $type);
} else {
$unionType[] = new Node\Identifier($type);
}
}
return new Node\UnionType($unionType);
}
return $this->getTypeWithNullableOrNot($reflection);
}
public function getNodeFromReflectionParameter(ReflectionParameter $parameter): Node\Param
{
$result = new Node\Param(
new Node\Expr\Variable($parameter->getName())
);
if ($parameter->isDefaultValueAvailable()) {
$result->default = $this->getExprFromValue($parameter->getDefaultValue());
}
if ($parameter->hasType()) {
/* @phpstan-ignore-next-line */
$result->type = $this->getNodeFromReflectionType($parameter->getType());
}
if ($parameter->isPassedByReference()) {
$result->byRef = true;
}
if ($parameter->isVariadic()) {
$result->variadic = true;
}
return $result;
}
public function getExprFromValue($value): Node\Expr
{
return match (gettype($value)) {
'array' => value(function ($value) {
$isList = ! Arr::isAssoc($value);
$result = [];
foreach ($value as $i => $item) {
$key = null;
if (! $isList) {
$key = is_int($i) ? new Node\Scalar\LNumber($i) : new Node\Scalar\String_($i);
}
$result[] = new Node\Expr\ArrayItem($this->getExprFromValue($item), $key);
}
return new Node\Expr\Array_($result, [
'kind' => Node\Expr\Array_::KIND_SHORT,
]);
}, $value),
'string' => new Node\Scalar\String_($value),
'integer' => new Node\Scalar\LNumber($value),
'double' => new Node\Scalar\DNumber($value),
'NULL' => new Node\Expr\ConstFetch(new Node\Name('null')),
'boolean' => new Node\Expr\ConstFetch(new Node\Name($value ? 'true' : 'false')),
'object' => $this->getExprFromObject($value),
default => throw new InvalidArgumentException($value . ' is invalid'),
};
}
/**
* @return Node\Stmt\ClassMethod[]
*/
public function getAllMethodsFromStmts(array $stmts, bool $withTrait = false): array
{
$methods = [];
foreach ($stmts as $namespace) {
if (! $namespace instanceof Node\Stmt\Namespace_) {
continue;
}
/** @var string[] $uses */
$uses = [];
foreach ($namespace->stmts as $class) {
if ($class instanceof Node\Stmt\Use_) {
foreach ($class->uses as $use) {
$uses[$use->name->getLast()] = $use->name->toString();
}
continue;
}
if (! $class instanceof Node\Stmt\Class_ && ! $class instanceof Node\Stmt\Interface_ && ! $class instanceof Node\Stmt\Trait_) {
continue;
}
foreach ($class->getMethods() as $method) {
$methods[] = $method;
}
if ($withTrait) {
foreach ($class->stmts as $stmt) {
if ($stmt instanceof Node\Stmt\TraitUse) {
foreach ($stmt->traits as $trait) {
$traitString = $trait->toString();
$traitParts = $trait->getParts();
$firstPart = $trait->getFirst();
if (isset($uses[$firstPart])) {
$traitName = $uses[$firstPart] . substr($traitString, strlen($firstPart));
} else {
if (count($traitParts) == 1) {
$traitName = $namespace->name->toString() . '\\' . $traitString;
} else {
$traitName = $traitString;
}
}
$traitNodes = $this->parser->parse(file_get_contents((new ReflectionClass($traitName))->getFileName()));
$methods = array_merge($methods, $this->getAllMethodsFromStmts($traitNodes, true));
}
}
}
}
}
}
return $methods;
}
/**
* Convert type name to appropriate Node type.
*/
public function getNodeByTypeString(string $typeName, bool $nullable = false): Node
{
if (in_array($typeName, PhpParser::TYPES)) {
$type = new Node\Identifier($typeName);
} else {
$type = new Node\Name('\\' . $typeName);
}
if ($nullable && $typeName !== 'mixed') {
return new Node\NullableType($type);
}
return $type;
}
private function getExprFromObject(object $value)
{
$ref = new ReflectionClass($value);
if (method_exists($ref, 'isEnum') && $ref->isEnum()) {
return new Node\Expr\ClassConstFetch(
new Node\Name('\\' . $value::class),
$value->name
);
}
return new Node\Expr\New_(
new Node\Name\FullyQualified($value::class)
);
}
private function getTypeWithNullableOrNot(ReflectionType $reflection): Node
{
if (! $reflection instanceof ReflectionNamedType) {
throw new ReflectionException('ReflectionType must be ReflectionNamedType.');
}
return $this->getNodeByTypeString($reflection->getName(), $reflection->allowsNull());
}
}