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

nette / php-generator / 16783678746

06 Aug 2025 05:13PM UTC coverage: 92.006%. Remained the same
16783678746

push

github

dg
updated phpstan-baseline

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.66
/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
                        $trait = $class->addTrait($trait);
1✔
132
                        foreach ($resolutions as $resolution) {
1✔
133
                                $trait->addResolution($resolution);
1✔
134
                        }
135
                        $resolutions = [];
1✔
136
                }
137

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

147
                if ($consts) {
1✔
148
                        $class->setConstants($consts);
1✔
149
                }
150
                if ($cases) {
1✔
151
                        $class->setCases($cases);
×
152
                }
153

154
                return $class;
1✔
155
        }
156

157

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

173
                return $method;
1✔
174
        }
175

176

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

187
                $function->setAttributes($this->getAttributes($from));
1✔
188
                $function->setReturnType((string) $from->getReturnType());
1✔
189

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

195
                        $function->setBody($this->getExtractor($from->getFileName())->extractFunctionBody($from->name));
1✔
196
                }
197

198
                return $function;
1✔
199
        }
200

201

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

210

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

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

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

241
                $param->setAttributes($this->getAttributes($from));
1✔
242
                return $param;
1✔
243
        }
244

245

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

257

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

267

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

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

290

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

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

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

327

328
        public function fromObject(object $obj): Literal
329
        {
330
                return new Literal('new \\' . $obj::class . '(/* unknown */)');
×
331
        }
332

333

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

340

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

347

348
        /** @return Attribute[] */
349
        private function getAttributes($from): array
350
        {
351
                return array_map(function ($attr) {
1✔
352
                        $args = $attr->getArguments();
1✔
353
                        foreach ($args as &$arg) {
1✔
354
                                if (is_object($arg)) {
1✔
355
                                        $arg = $this->fromObject($arg);
×
356
                                }
357
                        }
358

359
                        return new Attribute($attr->getName(), $args);
1✔
360
                }, $from->getAttributes());
1✔
361
        }
362

363

364
        private function getVisibility(\ReflectionProperty|\ReflectionMethod|\ReflectionClassConstant $from): string
1✔
365
        {
366
                return $from->isPrivate()
1✔
367
                        ? Visibility::Private
1✔
368
                        : ($from->isProtected() ? Visibility::Protected : Visibility::Public);
1✔
369
        }
370

371

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