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

nette / php-generator / 20322923947

18 Dec 2025 01:29AM UTC coverage: 93.614% (+0.07%) from 93.547%
20322923947

push

github

dg
Factory::fromClassReflection() refactoring

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

12 existing lines in 1 file 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.44
/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
                $from = $from->isEnum() ? new \ReflectionEnum($from->getName()) : $from;
1✔
41
                $class = $this->createClassObject($from);
1✔
42
                $this->setupInheritance($class, $from);
1✔
43
                $this->populateMembers($class, $from, $withBodies);
1✔
44
                return $class;
1✔
45
        }
46

47

48
        private function createClassObject(\ReflectionClass $from): ClassLike
1✔
49
        {
50
                if ($from->isEnum()) {
1✔
51
                        $class = new EnumType($from->getShortName());
1✔
52
                } elseif ($from->isAnonymous()) {
1✔
53
                        $class = new ClassType;
1✔
54
                } elseif ($from->isInterface()) {
1✔
55
                        $class = new InterfaceType($from->getShortName());
1✔
56
                } elseif ($from->isTrait()) {
1✔
57
                        $class = new TraitType($from->getShortName());
1✔
58
                } else {
59
                        $class = new ClassType($from->getShortName());
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
                }
64
                if (!$from->isAnonymous()) {
1✔
65
                        (new PhpNamespace($from->getNamespaceName()))->add($class);
1✔
66
                }
67
                return $class;
1✔
68
        }
69

70

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

79
                if ($from->isInterface()) {
1✔
80
                        $class->setExtends($ifaces);
1✔
81
                } elseif ($ifaces) {
1✔
82
                        $class->setImplements($ifaces);
1✔
83
                }
84

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

93

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

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

116
                if ($props) {
1✔
117
                        $class->setProperties($props);
1✔
118
                }
119

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

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

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

149
                $class->setMethods($methods);
1✔
150

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

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

170
                if ($consts) {
1✔
171
                        $class->setConstants($consts);
1✔
172
                }
173
                if ($cases) {
1✔
174
                        $class->setCases($cases);
1✔
175
                }
176
        }
1✔
177

178

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

194
                return $method;
1✔
195
        }
196

197

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

208
                $function->setAttributes($this->getAttributes($from));
1✔
209
                $function->setReturnType((string) $from->getReturnType());
1✔
210

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

216
                        $function->setBody($this->getExtractor($from->getFileName())->extractFunctionBody($from->name));
1✔
217
                }
218

219
                return $function;
1✔
220
        }
221

222

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

231

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

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

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

262
                $param->setAttributes($this->getAttributes($from));
1✔
263
                return $param;
1✔
264
        }
265

266

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

278

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

288

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

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

311

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

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

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

348

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

354

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

361

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

368

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

380
                        return new Attribute($attr->getName(), $args);
1✔
381
                }, $from->getAttributes());
1✔
382
        }
383

384

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

392

393
        private function getExtractor(string $file): Extractor
1✔
394
        {
395
                $cache = &$this->extractorCache[$file];
1✔
396
                $cache ??= new Extractor(file_get_contents($file));
1✔
397
                return $cache;
1✔
398
        }
399
}
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