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

nette / php-generator / 16781746162

06 Aug 2025 03:44PM UTC coverage: 92.006%. Remained the same
16781746162

push

github

dg
added support for final promoted property

14 of 14 new or added lines in 4 files covered. (100.0%)

15 existing lines in 4 files now uncovered.

1761 of 1914 relevant lines covered (92.01%)

0.92 hits per line

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

80.38
/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
                $enumIface = null;
1✔
41
                if (PHP_VERSION_ID >= 80100 && $from->isEnum()) {
1✔
42
                        $class = new EnumType($from->getShortName(), new PhpNamespace($from->getNamespaceName()));
×
43
                        $from = new \ReflectionEnum($from->getName());
×
44
                        $enumIface = $from->isBacked() ? \BackedEnum::class : \UnitEnum::class;
×
45
                } elseif ($from->isAnonymous()) {
1✔
46
                        $class = new ClassType;
1✔
47
                } elseif ($from->isInterface()) {
1✔
48
                        $class = new InterfaceType($from->getShortName(), new PhpNamespace($from->getNamespaceName()));
1✔
49
                } elseif ($from->isTrait()) {
1✔
50
                        $class = new TraitType($from->getShortName(), new PhpNamespace($from->getNamespaceName()));
1✔
51
                } else {
52
                        $class = new ClassType($from->getShortName(), new PhpNamespace($from->getNamespaceName()));
1✔
53
                        $class->setFinal($from->isFinal() && $class->isClass());
1✔
54
                        $class->setAbstract($from->isAbstract() && $class->isClass());
1✔
55
                        $class->setReadOnly(PHP_VERSION_ID >= 80200 && $from->isReadOnly());
1✔
56
                }
57

58
                $ifaces = $from->getInterfaceNames();
1✔
59
                foreach ($ifaces as $iface) {
1✔
60
                        $ifaces = array_filter($ifaces, fn(string $item): bool => !is_subclass_of($iface, $item));
1✔
61
                }
62

63
                if ($from->isInterface()) {
1✔
64
                        $class->setExtends($ifaces);
1✔
65
                } elseif ($ifaces) {
1✔
66
                        $ifaces = array_diff($ifaces, [$enumIface]);
1✔
67
                        $class->setImplements($ifaces);
1✔
68
                }
69

70
                $class->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
1✔
71
                $class->setAttributes($this->getAttributes($from));
1✔
72
                if ($from->getParentClass()) {
1✔
73
                        $class->setExtends($from->getParentClass()->name);
1✔
74
                        $class->setImplements(array_diff($class->getImplements(), $from->getParentClass()->getInterfaceNames()));
1✔
75
                }
76

77
                $props = [];
1✔
78
                foreach ($from->getProperties() as $prop) {
1✔
79
                        $declaringClass = Reflection::getPropertyDeclaringClass($prop);
1✔
80

81
                        if ($prop->isDefault()
1✔
82
                                && $declaringClass->name === $from->name
1✔
83
                                && !$prop->isPromoted()
1✔
84
                                && !$class->isEnum()
1✔
85
                        ) {
86
                                $props[] = $p = $this->fromPropertyReflection($prop);
1✔
87
                                if ($withBodies) {
1✔
88
                                        $hookBodies ??= $this->getExtractor($declaringClass->getFileName())->extractPropertyHookBodies($declaringClass->name);
1✔
89
                                        foreach ($hookBodies[$prop->getName()] ?? [] as $hookType => [$body, $short]) {
1✔
90
                                                $p->getHook($hookType)->setBody($body, short: $short);
×
91
                                        }
92
                                }
93
                        }
94
                }
95

96
                if ($props) {
1✔
97
                        $class->setProperties($props);
1✔
98
                }
99

100
                $methods = $resolutions = [];
1✔
101
                foreach ($from->getMethods() as $method) {
1✔
102
                        $declaringMethod = Reflection::getMethodDeclaringMethod($method);
1✔
103
                        $declaringClass = $declaringMethod->getDeclaringClass();
1✔
104

105
                        if (
106
                                $declaringClass->name === $from->name
1✔
107
                                && (!$enumIface || !method_exists($enumIface, $method->name))
1✔
108
                        ) {
109
                                $methods[] = $m = $this->fromMethodReflection($method);
1✔
110
                                if ($withBodies) {
1✔
111
                                        $bodies = &$this->bodyCache[$declaringClass->name];
1✔
112
                                        $bodies ??= $this->getExtractor($declaringClass->getFileName())->extractMethodBodies($declaringClass->name);
1✔
113
                                        if (isset($bodies[$declaringMethod->name])) {
1✔
114
                                                $m->setBody($bodies[$declaringMethod->name]);
1✔
115
                                        }
116
                                }
117
                        }
118

119
                        $modifier = $declaringMethod->getModifiers() !== $method->getModifiers()
1✔
120
                                ? ' ' . $this->getVisibility($method)
1✔
121
                                : null;
1✔
122
                        $alias = $declaringMethod->name !== $method->name ? ' ' . $method->name : '';
1✔
123
                        if ($modifier || $alias) {
1✔
124
                                $resolutions[] = $declaringMethod->name . ' as' . $modifier . $alias;
1✔
125
                        }
126
                }
127

128
                $class->setMethods($methods);
1✔
129

130
                foreach ($from->getTraitNames() as $trait) {
1✔
131
                        $class->addTrait($trait, $resolutions);
1✔
132
                        $resolutions = [];
1✔
133
                }
134

135
                $consts = $cases = [];
1✔
136
                foreach ($from->getReflectionConstants() as $const) {
1✔
137
                        if ($class->isEnum() && $from->hasCase($const->name)) {
1✔
138
                                $cases[] = $this->fromCaseReflection($const);
×
139
                        } elseif ($const->getDeclaringClass()->name === $from->name) {
1✔
140
                                $consts[] = $this->fromConstantReflection($const);
1✔
141
                        }
142
                }
143

144
                if ($consts) {
1✔
145
                        $class->setConstants($consts);
1✔
146
                }
147
                if ($cases) {
1✔
148
                        $class->setCases($cases);
×
149
                }
150

151
                return $class;
1✔
152
        }
153

154

155
        public function fromMethodReflection(\ReflectionMethod $from): Method
1✔
156
        {
157
                $method = new Method($from->name);
1✔
158
                $method->setParameters(array_map([$this, 'fromParameterReflection'], $from->getParameters()));
1✔
159
                $method->setStatic($from->isStatic());
1✔
160
                $isInterface = $from->getDeclaringClass()->isInterface();
1✔
161
                $method->setVisibility($isInterface ? null : $this->getVisibility($from));
1✔
162
                $method->setFinal($from->isFinal());
1✔
163
                $method->setAbstract($from->isAbstract() && !$isInterface);
1✔
164
                $method->setReturnReference($from->returnsReference());
1✔
165
                $method->setVariadic($from->isVariadic());
1✔
166
                $method->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
1✔
167
                $method->setAttributes($this->getAttributes($from));
1✔
168
                $method->setReturnType((string) $from->getReturnType());
1✔
169

170
                return $method;
1✔
171
        }
172

173

174
        public function fromFunctionReflection(\ReflectionFunction $from, bool $withBody = false): GlobalFunction|Closure
1✔
175
        {
176
                $function = $from->isClosure() ? new Closure : new GlobalFunction($from->name);
1✔
177
                $function->setParameters(array_map([$this, 'fromParameterReflection'], $from->getParameters()));
1✔
178
                $function->setReturnReference($from->returnsReference());
1✔
179
                $function->setVariadic($from->isVariadic());
1✔
180
                if (!$from->isClosure()) {
1✔
181
                        $function->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
1✔
182
                }
183

184
                $function->setAttributes($this->getAttributes($from));
1✔
185
                $function->setReturnType((string) $from->getReturnType());
1✔
186

187
                if ($withBody) {
1✔
188
                        if ($from->isClosure() || $from->isInternal()) {
1✔
189
                                throw new Nette\NotSupportedException('The $withBody parameter cannot be used for closures or internal functions.');
×
190
                        }
191

192
                        $function->setBody($this->getExtractor($from->getFileName())->extractFunctionBody($from->name));
1✔
193
                }
194

195
                return $function;
1✔
196
        }
197

198

199
        public function fromCallable(callable $from): Method|GlobalFunction|Closure
1✔
200
        {
201
                $ref = Nette\Utils\Callback::toReflection($from);
1✔
202
                return $ref instanceof \ReflectionMethod
1✔
203
                        ? $this->fromMethodReflection($ref)
1✔
204
                        : $this->fromFunctionReflection($ref);
1✔
205
        }
206

207

208
        public function fromParameterReflection(\ReflectionParameter $from): Parameter
1✔
209
        {
210
                if ($from->isPromoted()) {
1✔
211
                        $property = $from->getDeclaringClass()->getProperty($from->name);
1✔
212
                        $param = (new PromotedParameter($from->name))
1✔
213
                                ->setVisibility($this->getVisibility($property))
1✔
214
                                ->setReadOnly(PHP_VERSION_ID >= 80100 && $property->isReadonly())
1✔
215
                                ->setFinal(PHP_VERSION_ID >= 80500 && $property->isFinal() && !$property->isPrivateSet());
1✔
216
                        $this->addHooks($property, $param);
1✔
217
                } else {
218
                        $param = new Parameter($from->name);
1✔
219
                }
220
                $param->setReference($from->isPassedByReference());
1✔
221
                $param->setType((string) $from->getType());
1✔
222

223
                if ($from->isDefaultValueAvailable()) {
1✔
224
                        if ($from->isDefaultValueConstant()) {
1✔
225
                                $parts = explode('::', $from->getDefaultValueConstantName());
1✔
226
                                if (count($parts) > 1) {
1✔
227
                                        $parts[0] = Helpers::tagName($parts[0]);
1✔
228
                                }
229

230
                                $param->setDefaultValue(new Literal(implode('::', $parts)));
1✔
231
                        } elseif (is_object($from->getDefaultValue())) {
1✔
UNCOV
232
                                $param->setDefaultValue($this->fromObject($from->getDefaultValue()));
×
233
                        } else {
234
                                $param->setDefaultValue($from->getDefaultValue());
1✔
235
                        }
236
                }
237

238
                $param->setAttributes($this->getAttributes($from));
1✔
239
                return $param;
1✔
240
        }
241

242

243
        public function fromConstantReflection(\ReflectionClassConstant $from): Constant
1✔
244
        {
245
                $const = new Constant($from->name);
1✔
246
                $const->setValue($from->getValue());
1✔
247
                $const->setVisibility($this->getVisibility($from));
1✔
248
                $const->setFinal(PHP_VERSION_ID >= 80100 && $from->isFinal());
1✔
249
                $const->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
1✔
250
                $const->setAttributes($this->getAttributes($from));
1✔
251
                return $const;
1✔
252
        }
253

254

255
        public function fromCaseReflection(\ReflectionClassConstant $from): EnumCase
256
        {
UNCOV
257
                $const = new EnumCase($from->name);
×
258
                $const->setValue($from->getValue()->value ?? null);
×
259
                $const->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
×
260
                $const->setAttributes($this->getAttributes($from));
×
261
                return $const;
×
262
        }
263

264

265
        public function fromPropertyReflection(\ReflectionProperty $from): Property
1✔
266
        {
267
                $defaults = $from->getDeclaringClass()->getDefaultProperties();
1✔
268
                $prop = new Property($from->name);
1✔
269
                $prop->setValue($defaults[$prop->getName()] ?? null);
1✔
270
                $prop->setStatic($from->isStatic());
1✔
271
                $prop->setVisibility($this->getVisibility($from));
1✔
272
                $prop->setType((string) $from->getType());
1✔
273
                $prop->setInitialized($from->hasType() && array_key_exists($prop->getName(), $defaults));
1✔
274
                $prop->setReadOnly(PHP_VERSION_ID >= 80100 && $from->isReadOnly());
1✔
275
                $prop->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
1✔
276
                $prop->setAttributes($this->getAttributes($from));
1✔
277

278
                if (PHP_VERSION_ID >= 80400) {
1✔
UNCOV
279
                        $this->addHooks($from, $prop);
×
280
                        $isInterface = $from->getDeclaringClass()->isInterface();
×
281
                        $prop->setFinal($from->isFinal() && !$prop->isPrivate(PropertyAccessMode::Set));
×
282
                        $prop->setAbstract($from->isAbstract() && !$isInterface);
×
283
                }
284
                return $prop;
1✔
285
        }
286

287

288
        private function addHooks(\ReflectionProperty $from, Property|PromotedParameter $prop): void
1✔
289
        {
290
                if (PHP_VERSION_ID < 80400) {
1✔
291
                        return;
1✔
292
                }
293

UNCOV
294
                $getV = $this->getVisibility($from);
×
295
                $setV = $from->isPrivateSet()
×
296
                        ? Visibility::Private
×
297
                        : ($from->isProtectedSet() ? Visibility::Protected : $getV);
×
298
                $defaultSetV = $from->isReadOnly() && $getV !== Visibility::Private
×
299
                        ? Visibility::Protected
×
300
                        : $getV;
×
301
                if ($setV !== $defaultSetV) {
×
302
                        $prop->setVisibility($getV === Visibility::Public ? null : $getV, $setV);
×
303
                }
304

UNCOV
305
                foreach ($from->getHooks() as $type => $hook) {
×
306
                        $params = $hook->getParameters();
×
307
                        if (
UNCOV
308
                                count($params) === 1
×
309
                                && $params[0]->getName() === 'value'
×
310
                                && $params[0]->getType() == $from->getType() // intentionally ==
×
311
                        ) {
UNCOV
312
                                $params = [];
×
313
                        }
UNCOV
314
                        $prop->addHook($type)
×
315
                                ->setParameters(array_map([$this, 'fromParameterReflection'], $params))
×
316
                                ->setAbstract($hook->isAbstract())
×
317
                                ->setFinal($hook->isFinal())
×
318
                                ->setReturnReference($hook->returnsReference())
×
319
                                ->setComment(Helpers::unformatDocComment((string) $hook->getDocComment()))
×
320
                                ->setAttributes($this->getAttributes($hook));
×
321
                }
322
        }
323

324

325
        public function fromObject(object $obj): Literal
326
        {
UNCOV
327
                return new Literal('new \\' . $obj::class . '(/* unknown */)');
×
328
        }
329

330

331
        public function fromClassCode(string $code): ClassLike
1✔
332
        {
333
                $classes = $this->fromCode($code)->getClasses();
1✔
334
                return reset($classes) ?: throw new Nette\InvalidStateException('The code does not contain any class.');
1✔
335
        }
336

337

338
        public function fromCode(string $code): PhpFile
1✔
339
        {
340
                $reader = new Extractor($code);
1✔
341
                return $reader->extractAll();
1✔
342
        }
343

344

345
        private function getAttributes($from): array
346
        {
347
                return array_map(function ($attr) {
1✔
348
                        $args = $attr->getArguments();
1✔
349
                        foreach ($args as &$arg) {
1✔
350
                                if (is_object($arg)) {
1✔
UNCOV
351
                                        $arg = $this->fromObject($arg);
×
352
                                }
353
                        }
354

355
                        return new Attribute($attr->getName(), $args);
1✔
356
                }, $from->getAttributes());
1✔
357
        }
358

359

360
        private function getVisibility($from): string
361
        {
362
                return $from->isPrivate()
1✔
363
                        ? Visibility::Private
1✔
364
                        : ($from->isProtected() ? Visibility::Protected : Visibility::Public);
1✔
365
        }
366

367

368
        private function getExtractor(string $file): Extractor
1✔
369
        {
370
                $cache = &$this->extractorCache[$file];
1✔
371
                $cache ??= new Extractor(file_get_contents($file));
1✔
372
                return $cache;
1✔
373
        }
374
}
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