-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
Factory.php
318 lines (257 loc) · 9.9 KB
/
Factory.php
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Nette\PhpGenerator;
use Nette;
use Nette\Utils\Reflection;
/**
* Creates a representations based on reflection or source code.
*/
final class Factory
{
/** @var string[][] */
private array $bodyCache = [];
/** @var Extractor[] */
private array $extractorCache = [];
/** @param \ReflectionClass<object> $from */
public function fromClassReflection(
\ReflectionClass $from,
bool $withBodies = false,
): ClassLike
{
if ($withBodies && ($from->isAnonymous() || $from->isInternal())) {
throw new Nette\NotSupportedException('The $withBodies parameter cannot be used for anonymous or internal classes.');
}
$enumIface = null;
if (PHP_VERSION_ID >= 80100 && $from->isEnum()) {
$class = new EnumType($from->getShortName(), new PhpNamespace($from->getNamespaceName()));
$from = new \ReflectionEnum($from->getName());
$enumIface = $from->isBacked() ? \BackedEnum::class : \UnitEnum::class;
} elseif ($from->isAnonymous()) {
$class = new ClassType;
} elseif ($from->isInterface()) {
$class = new InterfaceType($from->getShortName(), new PhpNamespace($from->getNamespaceName()));
} elseif ($from->isTrait()) {
$class = new TraitType($from->getShortName(), new PhpNamespace($from->getNamespaceName()));
} else {
$class = new ClassType($from->getShortName(), new PhpNamespace($from->getNamespaceName()));
$class->setFinal($from->isFinal() && $class->isClass());
$class->setAbstract($from->isAbstract() && $class->isClass());
$class->setReadOnly(PHP_VERSION_ID >= 80200 && $from->isReadOnly());
}
$ifaces = $from->getInterfaceNames();
foreach ($ifaces as $iface) {
$ifaces = array_filter($ifaces, fn(string $item): bool => !is_subclass_of($iface, $item));
}
if ($from->isInterface()) {
$class->setExtends($ifaces);
} elseif ($ifaces) {
$ifaces = array_diff($ifaces, [$enumIface]);
$class->setImplements($ifaces);
}
$class->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
$class->setAttributes($this->getAttributes($from));
if ($from->getParentClass()) {
$class->setExtends($from->getParentClass()->name);
$class->setImplements(array_diff($class->getImplements(), $from->getParentClass()->getInterfaceNames()));
}
$props = [];
foreach ($from->getProperties() as $prop) {
$declaringClass = Reflection::getPropertyDeclaringClass($prop);
if ($prop->isDefault()
&& $declaringClass->name === $from->name
&& !$prop->isPromoted()
&& !$class->isEnum()
) {
$props[] = $this->fromPropertyReflection($prop);
}
}
if ($props) {
$class->setProperties($props);
}
$methods = $resolutions = [];
foreach ($from->getMethods() as $method) {
$declaringMethod = Reflection::getMethodDeclaringMethod($method);
$declaringClass = $declaringMethod->getDeclaringClass();
if (
$declaringClass->name === $from->name
&& (!$enumIface || !method_exists($enumIface, $method->name))
) {
$methods[] = $m = $this->fromMethodReflection($method);
if ($withBodies) {
$bodies = &$this->bodyCache[$declaringClass->name];
$bodies ??= $this->getExtractor($declaringClass->getFileName())->extractMethodBodies($declaringClass->name);
if (isset($bodies[$declaringMethod->name])) {
$m->setBody($bodies[$declaringMethod->name]);
}
}
}
$modifier = $declaringMethod->getModifiers() !== $method->getModifiers()
? ' ' . $this->getVisibility($method)
: null;
$alias = $declaringMethod->name !== $method->name ? ' ' . $method->name : '';
if ($modifier || $alias) {
$resolutions[] = $declaringMethod->name . ' as' . $modifier . $alias;
}
}
$class->setMethods($methods);
foreach ($from->getTraitNames() as $trait) {
$class->addTrait($trait, $resolutions);
$resolutions = [];
}
$consts = $cases = [];
foreach ($from->getReflectionConstants() as $const) {
if ($class->isEnum() && $from->hasCase($const->name)) {
$cases[] = $this->fromCaseReflection($const);
} elseif ($const->getDeclaringClass()->name === $from->name) {
$consts[] = $this->fromConstantReflection($const);
}
}
if ($consts) {
$class->setConstants($consts);
}
if ($cases) {
$class->setCases($cases);
}
return $class;
}
public function fromMethodReflection(\ReflectionMethod $from): Method
{
$method = new Method($from->name);
$method->setParameters(array_map([$this, 'fromParameterReflection'], $from->getParameters()));
$method->setStatic($from->isStatic());
$isInterface = $from->getDeclaringClass()->isInterface();
$method->setVisibility($isInterface ? null : $this->getVisibility($from));
$method->setFinal($from->isFinal());
$method->setAbstract($from->isAbstract() && !$isInterface);
$method->setReturnReference($from->returnsReference());
$method->setVariadic($from->isVariadic());
$method->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
$method->setAttributes($this->getAttributes($from));
$method->setReturnType((string) $from->getReturnType());
return $method;
}
public function fromFunctionReflection(\ReflectionFunction $from, bool $withBody = false): GlobalFunction|Closure
{
$function = $from->isClosure() ? new Closure : new GlobalFunction($from->name);
$function->setParameters(array_map([$this, 'fromParameterReflection'], $from->getParameters()));
$function->setReturnReference($from->returnsReference());
$function->setVariadic($from->isVariadic());
if (!$from->isClosure()) {
$function->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
}
$function->setAttributes($this->getAttributes($from));
$function->setReturnType((string) $from->getReturnType());
if ($withBody) {
if ($from->isClosure() || $from->isInternal()) {
throw new Nette\NotSupportedException('The $withBody parameter cannot be used for closures or internal functions.');
}
$function->setBody($this->getExtractor($from->getFileName())->extractFunctionBody($from->name));
}
return $function;
}
public function fromCallable(callable $from): Method|GlobalFunction|Closure
{
$ref = Nette\Utils\Callback::toReflection($from);
return $ref instanceof \ReflectionMethod
? $this->fromMethodReflection($ref)
: $this->fromFunctionReflection($ref);
}
public function fromParameterReflection(\ReflectionParameter $from): Parameter
{
$param = $from->isPromoted()
? new PromotedParameter($from->name)
: new Parameter($from->name);
$param->setReference($from->isPassedByReference());
$param->setType((string) $from->getType());
if ($from->isDefaultValueAvailable()) {
if ($from->isDefaultValueConstant()) {
$parts = explode('::', $from->getDefaultValueConstantName());
if (count($parts) > 1) {
$parts[0] = Helpers::tagName($parts[0]);
}
$param->setDefaultValue(new Literal(implode('::', $parts)));
} elseif (is_object($from->getDefaultValue())) {
$param->setDefaultValue($this->fromObject($from->getDefaultValue()));
} else {
$param->setDefaultValue($from->getDefaultValue());
}
$param->setNullable($param->isNullable() && $param->getDefaultValue() !== null);
}
$param->setAttributes($this->getAttributes($from));
return $param;
}
public function fromConstantReflection(\ReflectionClassConstant $from): Constant
{
$const = new Constant($from->name);
$const->setValue($from->getValue());
$const->setVisibility($this->getVisibility($from));
$const->setFinal(PHP_VERSION_ID >= 80100 ? $from->isFinal() : false);
$const->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
$const->setAttributes($this->getAttributes($from));
return $const;
}
public function fromCaseReflection(\ReflectionClassConstant $from): EnumCase
{
$const = new EnumCase($from->name);
$const->setValue($from->getValue()->value ?? null);
$const->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
$const->setAttributes($this->getAttributes($from));
return $const;
}
public function fromPropertyReflection(\ReflectionProperty $from): Property
{
$defaults = $from->getDeclaringClass()->getDefaultProperties();
$prop = new Property($from->name);
$prop->setValue($defaults[$prop->getName()] ?? null);
$prop->setStatic($from->isStatic());
$prop->setVisibility($this->getVisibility($from));
$prop->setType((string) $from->getType());
$prop->setInitialized($from->hasType() && array_key_exists($prop->getName(), $defaults));
$prop->setReadOnly(PHP_VERSION_ID >= 80100 && $from->isReadOnly() && !(PHP_VERSION_ID >= 80200 && $from->getDeclaringClass()->isReadOnly()));
$prop->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
$prop->setAttributes($this->getAttributes($from));
return $prop;
}
public function fromObject(object $obj): Literal
{
return new Literal('new \\' . $obj::class . '(/* unknown */)');
}
public function fromClassCode(string $code): ClassLike
{
$classes = $this->fromCode($code)->getClasses();
return reset($classes) ?: throw new Nette\InvalidStateException('The code does not contain any class.');
}
public function fromCode(string $code): PhpFile
{
$reader = new Extractor($code);
return $reader->extractAll();
}
private function getAttributes($from): array
{
return array_map(function ($attr) {
$args = $attr->getArguments();
foreach ($args as &$arg) {
if (is_object($arg)) {
$arg = $this->fromObject($arg);
}
}
return new Attribute($attr->getName(), $args);
}, $from->getAttributes());
}
private function getVisibility($from): string
{
return $from->isPrivate()
? ClassLike::VisibilityPrivate
: ($from->isProtected() ? ClassLike::VisibilityProtected : ClassLike::VisibilityPublic);
}
private function getExtractor(string $file): Extractor
{
$cache = &$this->extractorCache[$file];
$cache ??= new Extractor(file_get_contents($file));
return $cache;
}
}