• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nette / php-generator / 20357425652

19 Dec 2025 02:04AM UTC coverage: 93.614%. Remained the same
20357425652

push

github

dg
Factory::fromClassReflection() refactoring

15 of 15 new or added lines in 1 file covered. (100.0%)

21 existing lines in 2 files now uncovered.

1803 of 1926 relevant lines covered (93.61%)

0.94 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.33
/src/PhpGenerator/Factory.php
1
<?php
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
declare(strict_types=1);
9

10
namespace Nette\PhpGenerator;
11

12
use Nette;
13
use Nette\Utils\Reflection;
14
use function array_diff, array_filter, array_key_exists, array_map, count, explode, file_get_contents, implode, is_object, is_subclass_of, method_exists, reset;
15
use const PHP_VERSION_ID;
16

17

18
/**
19
 * Creates a representations based on reflection or source code.
20
 */
21
final class Factory
22
{
23
        /** @var string[][]  */
24
        private array $bodyCache = [];
25

26
        /** @var Extractor[]  */
27
        private array $extractorCache = [];
28

29

30
        /** @param  \ReflectionClass<object>  $from */
31
        public function fromClassReflection(
1✔
32
                \ReflectionClass $from,
33
                bool $withBodies = false,
34
        ): ClassLike
35
        {
36
                if ($withBodies && ($from->isAnonymous() || $from->isInternal() || $from->isInterface())) {
1✔
37
                        throw new Nette\NotSupportedException('The $withBodies parameter cannot be used for anonymous or internal classes or interfaces.');
1✔
38
                }
39

40
                $class = $this->createClassObject($from);
1✔
41
                $this->setupInheritance($class, $from);
1✔
42
                $this->populateMembers($class, $from, $withBodies);
1✔
43
                return $class;
1✔
44
        }
45

46

47
        private function createClassObject(\ReflectionClass &$from): ClassLike
1✔
48
        {
49
                if ($from->isEnum()) {
1✔
50
                        $from = new \ReflectionEnum($from->getName());
1✔
51
                        return new EnumType($from->getName());
1✔
52
                } elseif ($from->isAnonymous()) {
1✔
53
                        return new ClassType;
1✔
54
                } elseif ($from->isInterface()) {
1✔
55
                        return new InterfaceType($from->getName());
1✔
56
                } elseif ($from->isTrait()) {
1✔
57
                        return new TraitType($from->getName());
1✔
58
                } else {
59
                        $class = new ClassType($from->getName());
1✔
60
                        $class->setFinal($from->isFinal() && $class->isClass());
1✔
61
                        $class->setAbstract($from->isAbstract() && $class->isClass());
1✔
62
                        $class->setReadOnly(PHP_VERSION_ID >= 80200 && $from->isReadOnly());
1✔
63
                        return $class;
1✔
64
                }
65
        }
66

67

68
        private function setupInheritance(ClassLike $class, \ReflectionClass $from): void
1✔
69
        {
70
                $ifaces = $from->getInterfaceNames();
1✔
71
                foreach ($ifaces as $iface) {
1✔
72
                        $ifaces = array_filter($ifaces, fn(string $item): bool => !is_subclass_of($iface, $item));
1✔
73
                }
74
                $ifaces = array_diff($ifaces, [\BackedEnum::class, \UnitEnum::class]);
1✔
75

76
                if ($from->isInterface()) {
1✔
77
                        $class->setExtends($ifaces);
1✔
78
                } elseif ($ifaces) {
1✔
79
                        $class->setImplements($ifaces);
1✔
80
                }
81

82
                $class->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
1✔
83
                $class->setAttributes($this->getAttributes($from));
1✔
84
                if ($from->getParentClass()) {
1✔
85
                        $class->setExtends($from->getParentClass()->name);
1✔
86
                        $class->setImplements(array_diff($class->getImplements(), $from->getParentClass()->getInterfaceNames()));
1✔
87
                }
88
        }
1✔
89

90

91
        private function populateMembers(ClassLike $class, \ReflectionClass $from, bool $withBodies): void
1✔
92
        {
93
                // Properties
94
                $props = [];
1✔
95
                foreach ($from->getProperties() as $prop) {
1✔
96
                        $declaringClass = Reflection::getPropertyDeclaringClass($prop);
1✔
97

98
                        if ($prop->isDefault()
1✔
99
                                && $declaringClass->name === $from->name
1✔
100
                                && !$prop->isPromoted()
1✔
101
                                && !$class->isEnum()
1✔
102
                        ) {
103
                                $props[] = $p = $this->fromPropertyReflection($prop);
1✔
104
                                if ($withBodies) {
1✔
105
                                        $hookBodies ??= $this->getExtractor($declaringClass->getFileName())->extractPropertyHookBodies($declaringClass->name);
1✔
106
                                        foreach ($hookBodies[$prop->getName()] ?? [] as $hookType => [$body, $short]) {
1✔
UNCOV
107
                                                $p->getHook($hookType)->setBody($body, short: $short);
×
108
                                        }
109
                                }
110
                        }
111
                }
112

113
                if ($props) {
1✔
114
                        $class->setProperties($props);
1✔
115
                }
116

117
                // Methods and trait resolutions
118
                $methods = $resolutions = [];
1✔
119
                foreach ($from->getMethods() as $method) {
1✔
120
                        $declaringMethod = Reflection::getMethodDeclaringMethod($method);
1✔
121
                        $declaringClass = $declaringMethod->getDeclaringClass();
1✔
122

123
                        if (
124
                                $declaringClass->name === $from->name
1✔
125
                                && (!$from->isEnum() || !method_exists($from->isBacked() ? \BackedEnum::class : \UnitEnum::class, $method->name))
1✔
126
                        ) {
127
                                $methods[] = $m = $this->fromMethodReflection($method);
1✔
128
                                if ($withBodies) {
1✔
129
                                        $bodies = &$this->bodyCache[$declaringClass->name];
1✔
130
                                        $bodies ??= $this->getExtractor($declaringClass->getFileName())->extractMethodBodies($declaringClass->name);
1✔
131
                                        if (isset($bodies[$declaringMethod->name])) {
1✔
132
                                                $m->setBody($bodies[$declaringMethod->name]);
1✔
133
                                        }
134
                                }
135
                        }
136

137
                        $modifier = $declaringMethod->getModifiers() !== $method->getModifiers()
1✔
138
                                ? ' ' . $this->getVisibility($method)->value
1✔
139
                                : null;
1✔
140
                        $alias = $declaringMethod->name !== $method->name ? ' ' . $method->name : '';
1✔
141
                        if ($modifier || $alias) {
1✔
142
                                $resolutions[] = $declaringMethod->name . ' as' . $modifier . $alias;
1✔
143
                        }
144
                }
145

146
                $class->setMethods($methods);
1✔
147

148
                // Traits
149
                foreach ($from->getTraitNames() as $trait) {
1✔
150
                        $trait = $class->addTrait($trait);
1✔
151
                        foreach ($resolutions as $resolution) {
1✔
152
                                $trait->addResolution($resolution);
1✔
153
                        }
154
                        $resolutions = [];
1✔
155
                }
156

157
                // Constants and enum cases
158
                $consts = $cases = [];
1✔
159
                foreach ($from->getReflectionConstants() as $const) {
1✔
160
                        if ($class->isEnum() && $from->hasCase($const->name)) {
1✔
161
                                $cases[] = $this->fromCaseReflection($const);
1✔
162
                        } elseif ($const->getDeclaringClass()->name === $from->name) {
1✔
163
                                $consts[] = $this->fromConstantReflection($const);
1✔
164
                        }
165
                }
166

167
                if ($consts) {
1✔
168
                        $class->setConstants($consts);
1✔
169
                }
170
                if ($cases) {
1✔
171
                        $class->setCases($cases);
1✔
172
                }
173
        }
1✔
174

175

176
        public function fromMethodReflection(\ReflectionMethod $from): Method
1✔
177
        {
178
                $method = new Method($from->name);
1✔
179
                $method->setParameters(array_map([$this, 'fromParameterReflection'], $from->getParameters()));
1✔
180
                $method->setStatic($from->isStatic());
1✔
181
                $isInterface = $from->getDeclaringClass()->isInterface();
1✔
182
                $method->setVisibility($isInterface ? null : $this->getVisibility($from));
1✔
183
                $method->setFinal($from->isFinal());
1✔
184
                $method->setAbstract($from->isAbstract() && !$isInterface);
1✔
185
                $method->setReturnReference($from->returnsReference());
1✔
186
                $method->setVariadic($from->isVariadic());
1✔
187
                $method->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
1✔
188
                $method->setAttributes($this->getAttributes($from));
1✔
189
                $method->setReturnType((string) $from->getReturnType());
1✔
190

191
                return $method;
1✔
192
        }
193

194

195
        public function fromFunctionReflection(\ReflectionFunction $from, bool $withBody = false): GlobalFunction|Closure
1✔
196
        {
197
                $function = $from->isClosure() ? new Closure : new GlobalFunction($from->name);
1✔
198
                $function->setParameters(array_map([$this, 'fromParameterReflection'], $from->getParameters()));
1✔
199
                $function->setReturnReference($from->returnsReference());
1✔
200
                $function->setVariadic($from->isVariadic());
1✔
201
                if (!$from->isClosure()) {
1✔
202
                        $function->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
1✔
203
                }
204

205
                $function->setAttributes($this->getAttributes($from));
1✔
206
                $function->setReturnType((string) $from->getReturnType());
1✔
207

208
                if ($withBody) {
1✔
209
                        if ($from->isClosure() || $from->isInternal()) {
1✔
UNCOV
210
                                throw new Nette\NotSupportedException('The $withBody parameter cannot be used for closures or internal functions.');
×
211
                        }
212

213
                        $function->setBody($this->getExtractor($from->getFileName())->extractFunctionBody($from->name));
1✔
214
                }
215

216
                return $function;
1✔
217
        }
218

219

220
        public function fromCallable(callable $from): Method|GlobalFunction|Closure
1✔
221
        {
222
                $ref = Nette\Utils\Callback::toReflection($from);
1✔
223
                return $ref instanceof \ReflectionMethod
1✔
224
                        ? $this->fromMethodReflection($ref)
1✔
225
                        : $this->fromFunctionReflection($ref);
1✔
226
        }
227

228

229
        public function fromParameterReflection(\ReflectionParameter $from): Parameter
1✔
230
        {
231
                if ($from->isPromoted()) {
1✔
232
                        $property = $from->getDeclaringClass()->getProperty($from->name);
1✔
233
                        $param = (new PromotedParameter($from->name))
1✔
234
                                ->setVisibility($this->getVisibility($property))
1✔
235
                                ->setReadOnly($property->isReadonly())
1✔
236
                                ->setFinal(PHP_VERSION_ID >= 80500 && $property->isFinal() && !$property->isPrivateSet());
1✔
237
                        $this->addHooks($property, $param);
1✔
238
                } else {
239
                        $param = new Parameter($from->name);
1✔
240
                }
241
                $param->setReference($from->isPassedByReference());
1✔
242
                $param->setType((string) $from->getType());
1✔
243

244
                if ($from->isDefaultValueAvailable()) {
1✔
245
                        if ($from->isDefaultValueConstant()) {
1✔
246
                                $parts = explode('::', $from->getDefaultValueConstantName());
1✔
247
                                if (count($parts) > 1) {
1✔
248
                                        $parts[0] = Helpers::tagName($parts[0]);
1✔
249
                                }
250

251
                                $param->setDefaultValue(new Literal(implode('::', $parts)));
1✔
252
                        } elseif (is_object($from->getDefaultValue())) {
1✔
253
                                $param->setDefaultValue($this->fromObject($from->getDefaultValue()));
1✔
254
                        } else {
255
                                $param->setDefaultValue($from->getDefaultValue());
1✔
256
                        }
257
                }
258

259
                $param->setAttributes($this->getAttributes($from));
1✔
260
                return $param;
1✔
261
        }
262

263

264
        public function fromConstantReflection(\ReflectionClassConstant $from): Constant
1✔
265
        {
266
                $const = new Constant($from->name);
1✔
267
                $const->setValue($from->getValue());
1✔
268
                $const->setVisibility($this->getVisibility($from));
1✔
269
                $const->setFinal($from->isFinal());
1✔
270
                $const->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
1✔
271
                $const->setAttributes($this->getAttributes($from));
1✔
272
                return $const;
1✔
273
        }
274

275

276
        public function fromCaseReflection(\ReflectionClassConstant $from): EnumCase
1✔
277
        {
278
                $const = new EnumCase($from->name);
1✔
279
                $const->setValue($from->getValue()->value ?? null);
1✔
280
                $const->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
1✔
281
                $const->setAttributes($this->getAttributes($from));
1✔
282
                return $const;
1✔
283
        }
284

285

286
        public function fromPropertyReflection(\ReflectionProperty $from): Property
1✔
287
        {
288
                $defaults = $from->getDeclaringClass()->getDefaultProperties();
1✔
289
                $prop = new Property($from->name);
1✔
290
                $prop->setValue($defaults[$prop->getName()] ?? null);
1✔
291
                $prop->setStatic($from->isStatic());
1✔
292
                $prop->setVisibility($this->getVisibility($from));
1✔
293
                $prop->setType((string) $from->getType());
1✔
294
                $prop->setInitialized($from->hasType() && array_key_exists($prop->getName(), $defaults));
1✔
295
                $prop->setReadOnly($from->isReadOnly());
1✔
296
                $prop->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
1✔
297
                $prop->setAttributes($this->getAttributes($from));
1✔
298

299
                if (PHP_VERSION_ID >= 80400) {
1✔
UNCOV
300
                        $this->addHooks($from, $prop);
×
UNCOV
301
                        $isInterface = $from->getDeclaringClass()->isInterface();
×
UNCOV
302
                        $prop->setFinal($from->isFinal() && !$prop->isPrivate(PropertyAccessMode::Set));
×
UNCOV
303
                        $prop->setAbstract($from->isAbstract() && !$isInterface);
×
304
                }
305
                return $prop;
1✔
306
        }
307

308

309
        private function addHooks(\ReflectionProperty $from, Property|PromotedParameter $prop): void
1✔
310
        {
311
                if (PHP_VERSION_ID < 80400) {
1✔
312
                        return;
1✔
313
                }
314

UNCOV
315
                $getV = $this->getVisibility($from);
×
UNCOV
316
                $setV = $from->isPrivateSet()
×
UNCOV
317
                        ? Visibility::Private
×
UNCOV
318
                        : ($from->isProtectedSet() ? Visibility::Protected : $getV);
×
UNCOV
319
                $defaultSetV = $from->isReadOnly() && $getV !== Visibility::Private
×
UNCOV
320
                        ? Visibility::Protected
×
321
                        : $getV;
×
322
                if ($setV !== $defaultSetV) {
×
323
                        $prop->setVisibility($getV === Visibility::Public ? null : $getV, $setV);
×
324
                }
325

UNCOV
326
                foreach ($from->getHooks() as $type => $hook) {
×
UNCOV
327
                        $params = $hook->getParameters();
×
328
                        if (
UNCOV
329
                                count($params) === 1
×
UNCOV
330
                                && $params[0]->getName() === 'value'
×
UNCOV
331
                                && $params[0]->getType() == $from->getType() // intentionally ==
×
332
                        ) {
UNCOV
333
                                $params = [];
×
334
                        }
UNCOV
335
                        $prop->addHook($type)
×
336
                                ->setParameters(array_map([$this, 'fromParameterReflection'], $params))
×
337
                                ->setAbstract($hook->isAbstract())
×
338
                                ->setFinal($hook->isFinal())
×
339
                                ->setReturnReference($hook->returnsReference())
×
340
                                ->setComment(Helpers::unformatDocComment((string) $hook->getDocComment()))
×
341
                                ->setAttributes($this->getAttributes($hook));
×
342
                }
343
        }
344

345

346
        public function fromObject(object $obj): Literal
1✔
347
        {
348
                return new Literal('new \\' . $obj::class . '(/* unknown */)');
1✔
349
        }
350

351

352
        public function fromClassCode(string $code): ClassLike
1✔
353
        {
354
                $classes = $this->fromCode($code)->getClasses();
1✔
355
                return reset($classes) ?: throw new Nette\InvalidStateException('The code does not contain any class.');
1✔
356
        }
357

358

359
        public function fromCode(string $code): PhpFile
1✔
360
        {
361
                $reader = new Extractor($code);
1✔
362
                return $reader->extractAll();
1✔
363
        }
364

365

366
        /** @return Attribute[] */
367
        private function getAttributes($from): array
368
        {
369
                return array_map(function ($attr) {
1✔
370
                        $args = $attr->getArguments();
1✔
371
                        foreach ($args as &$arg) {
1✔
372
                                if (is_object($arg)) {
1✔
373
                                        $arg = $this->fromObject($arg);
1✔
374
                                }
375
                        }
376

377
                        return new Attribute($attr->getName(), $args);
1✔
378
                }, $from->getAttributes());
1✔
379
        }
380

381

382
        private function getVisibility(\ReflectionProperty|\ReflectionMethod|\ReflectionClassConstant $from): Visibility
1✔
383
        {
384
                return $from->isPrivate()
1✔
385
                        ? Visibility::Private
1✔
386
                        : ($from->isProtected() ? Visibility::Protected : Visibility::Public);
1✔
387
        }
388

389

390
        private function getExtractor(string $file): Extractor
1✔
391
        {
392
                $cache = &$this->extractorCache[$file];
1✔
393
                $cache ??= new Extractor(file_get_contents($file));
1✔
394
                return $cache;
1✔
395
        }
396
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc