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

nette / php-generator / 9052482594

12 May 2024 03:36PM UTC coverage: 93.566% (-0.1%) from 93.686%
9052482594

push

github

dg
Factory, Extractor: sets flag readonly for promoted properties [Closes #158]

6 of 6 new or added lines in 3 files covered. (100.0%)

4 existing lines in 3 files now uncovered.

1556 of 1663 relevant lines covered (93.57%)

0.94 hits per line

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

98.94
/src/PhpGenerator/Extractor.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 PhpParser;
14
use PhpParser\Node;
15
use PhpParser\NodeFinder;
16
use PhpParser\ParserFactory;
17

18

19
/**
20
 * Extracts information from PHP code.
21
 * @internal
22
 */
23
final class Extractor
24
{
25
        private string $code;
26

27
        /** @var Node[] */
28
        private array $statements;
29
        private PhpParser\PrettyPrinterAbstract $printer;
30

31

32
        public function __construct(string $code)
1✔
33
        {
34
                if (!class_exists(ParserFactory::class)) {
1✔
35
                        throw new Nette\NotSupportedException("PHP-Parser is required to load method bodies, install package 'nikic/php-parser' 4.7 or newer.");
×
36
                }
37

38
                $this->printer = new PhpParser\PrettyPrinter\Standard;
1✔
39
                $this->parseCode($code);
1✔
40
        }
1✔
41

42

43
        private function parseCode(string $code): void
1✔
44
        {
45
                if (!str_starts_with($code, '<?php')) {
1✔
46
                        throw new Nette\InvalidStateException('The input string is not a PHP code.');
1✔
47
                }
48

49
                $this->code = Nette\Utils\Strings::normalizeNewlines($code);
1✔
50
                $parser = (new ParserFactory)->createForNewestSupportedVersion();
1✔
51
                $stmts = $parser->parse($this->code);
1✔
52

53
                $traverser = new PhpParser\NodeTraverser;
1✔
54
                $traverser->addVisitor(new PhpParser\NodeVisitor\ParentConnectingVisitor);
1✔
55
                $traverser->addVisitor(new PhpParser\NodeVisitor\NameResolver(null, ['preserveOriginalNames' => true]));
1✔
56
                $this->statements = $traverser->traverse($stmts);
1✔
57
        }
1✔
58

59

60
        /** @return array<string, string> */
61
        public function extractMethodBodies(string $className): array
1✔
62
        {
63
                $nodeFinder = new NodeFinder;
1✔
64
                $classNode = $nodeFinder->findFirst(
1✔
65
                        $this->statements,
1✔
66
                        fn(Node $node) => $node instanceof Node\Stmt\ClassLike && $node->namespacedName->toString() === $className,
1✔
67
                );
68

69
                $res = [];
1✔
70
                foreach ($nodeFinder->findInstanceOf($classNode, Node\Stmt\ClassMethod::class) as $methodNode) {
1✔
71
                        assert($methodNode instanceof Node\Stmt\ClassMethod);
72
                        if ($methodNode->stmts) {
1✔
73
                                $res[$methodNode->name->toString()] = $this->getReformattedContents($methodNode->stmts, 2);
1✔
74
                        }
75
                }
76

77
                return $res;
1✔
78
        }
79

80

81
        public function extractFunctionBody(string $name): ?string
1✔
82
        {
83
                $functionNode = (new NodeFinder)->findFirst(
1✔
84
                        $this->statements,
1✔
85
                        fn(Node $node) => $node instanceof Node\Stmt\Function_ && $node->namespacedName->toString() === $name,
1✔
86
                );
87
                assert($functionNode instanceof Node\Stmt\Function_);
88

89
                return $this->getReformattedContents($functionNode->stmts, 1);
1✔
90
        }
91

92

93
        /** @param  Node[]  $nodes */
94
        private function getReformattedContents(array $nodes, int $level): string
1✔
95
        {
96
                $body = $this->getNodeContents(...$nodes);
1✔
97
                $body = $this->performReplacements($body, $this->prepareReplacements($nodes, $level));
1✔
98
                return Helpers::unindent($body, $level);
1✔
99
        }
100

101

102
        /**
103
         * @param  Node[]  $nodes
104
         * @return array<array{int, int, string}>
105
         */
106
        private function prepareReplacements(array $nodes, int $level): array
1✔
107
        {
108
                $start = $this->getNodeStartPos($nodes[0]);
1✔
109
                $replacements = [];
1✔
110
                $indent = "\n" . str_repeat("\t", $level);
1✔
111
                (new NodeFinder)->find($nodes, function (Node $node) use (&$replacements, $start, $level, $indent) {
1✔
112
                        if ($node instanceof Node\Name\FullyQualified) {
1✔
113
                                if ($node->getAttribute('originalName') instanceof Node\Name) {
1✔
114
                                        $of = match (true) {
1✔
115
                                                $node->getAttribute('parent') instanceof Node\Expr\ConstFetch => PhpNamespace::NameConstant,
1✔
116
                                                $node->getAttribute('parent') instanceof Node\Expr\FuncCall => PhpNamespace::NameFunction,
1✔
117
                                                default => PhpNamespace::NameNormal,
1✔
118
                                        };
119
                                        $replacements[] = [
1✔
120
                                                $node->getStartFilePos() - $start,
1✔
121
                                                $node->getEndFilePos() - $start,
1✔
122
                                                Helpers::tagName($node->toCodeString(), $of),
1✔
123
                                        ];
124
                                }
125

126
                        } elseif (
127
                                $node instanceof Node\Scalar\String_
1✔
128
                                && in_array($node->getAttribute('kind'), [Node\Scalar\String_::KIND_SINGLE_QUOTED, Node\Scalar\String_::KIND_DOUBLE_QUOTED], true)
1✔
129
                                && str_contains($node->getAttribute('rawValue'), "\n")
1✔
130
                        ) { // multi-line strings -> single line
131
                                $replacements[] = [
1✔
132
                                        $node->getStartFilePos() - $start,
1✔
133
                                        $node->getEndFilePos() - $start,
1✔
134
                                        '"' . addcslashes($node->value, "\x00..\x1F\"") . '"',
1✔
135
                                ];
136

137
                        } elseif (
138
                                $node instanceof Node\Scalar\String_
1✔
139
                                && in_array($node->getAttribute('kind'), [Node\Scalar\String_::KIND_NOWDOC, Node\Scalar\String_::KIND_HEREDOC], true)
1✔
140
                                && Helpers::unindent($node->getAttribute('docIndentation'), $level) === $node->getAttribute('docIndentation')
1✔
141
                        ) { // fix indentation of NOWDOW/HEREDOC
142
                                $replacements[] = [
1✔
143
                                        $node->getStartFilePos() - $start,
1✔
144
                                        $node->getEndFilePos() - $start,
1✔
145
                                        str_replace("\n", $indent, $this->getNodeContents($node)),
1✔
146
                                ];
147

148
                        } elseif (
149
                                $node instanceof Node\Scalar\Encapsed
1✔
150
                                && $node->getAttribute('kind') === Node\Scalar\String_::KIND_DOUBLE_QUOTED
1✔
151
                        ) { // multi-line strings -> single line
152
                                foreach ($node->parts as $part) {
1✔
153
                                        if ($part instanceof Node\Scalar\EncapsedStringPart) {
1✔
154
                                                $replacements[] = [
1✔
155
                                                        $part->getStartFilePos() - $start,
1✔
156
                                                        $part->getEndFilePos() - $start,
1✔
157
                                                        addcslashes($part->value, "\x00..\x1F\""),
1✔
158
                                                ];
159
                                        }
160
                                }
161
                        } elseif (
162
                                $node instanceof Node\Scalar\Encapsed && $node->getAttribute('kind') === Node\Scalar\String_::KIND_HEREDOC
1✔
163
                                && Helpers::unindent($node->getAttribute('docIndentation'), $level) === $node->getAttribute('docIndentation')
1✔
164
                        ) { // fix indentation of HEREDOC
165
                                $replacements[] = [
1✔
166
                                        $tmp = $node->getStartFilePos() - $start + strlen($node->getAttribute('docLabel')) + 3, // <<<
1✔
167
                                        $tmp,
1✔
168
                                        $indent,
1✔
169
                                ];
170
                                $replacements[] = [
1✔
171
                                        $tmp = $node->getEndFilePos() - $start - strlen($node->getAttribute('docLabel')),
1✔
172
                                        $tmp,
1✔
173
                                        $indent,
1✔
174
                                ];
175
                                foreach ($node->parts as $part) {
1✔
176
                                        if ($part instanceof Node\Scalar\EncapsedStringPart) {
1✔
177
                                                $replacements[] = [
1✔
178
                                                        $part->getStartFilePos() - $start,
1✔
179
                                                        $part->getEndFilePos() - $start,
1✔
180
                                                        str_replace("\n", $indent, $this->getNodeContents($part)),
1✔
181
                                                ];
182
                                        }
183
                                }
184
                        }
185
                });
1✔
186
                return $replacements;
1✔
187
        }
188

189

190
        /** @param  array<array{int, int, string}>  $replacements */
191
        private function performReplacements(string $s, array $replacements): string
1✔
192
        {
193
                usort($replacements, fn($a, $b) => $b[0] <=> $a[0]);
1✔
194

195
                foreach ($replacements as [$start, $end, $replacement]) {
1✔
196
                        $s = substr_replace($s, $replacement, $start, $end - $start + 1);
1✔
197
                }
198

199
                return $s;
1✔
200
        }
201

202

203
        public function extractAll(): PhpFile
204
        {
205
                $phpFile = new PhpFile;
1✔
206

207
                if (
208
                        $this->statements
1✔
209
                        && !$this->statements[0] instanceof Node\Stmt\ClassLike
1✔
210
                        && !$this->statements[0] instanceof Node\Stmt\Function_
1✔
211
                ) {
212
                        $this->addCommentAndAttributes($phpFile, $this->statements[0]);
1✔
213
                }
214

215
                $namespaces = ['' => $this->statements];
1✔
216
                foreach ($this->statements as $node) {
1✔
217
                        if ($node instanceof Node\Stmt\Declare_
1✔
218
                                && $node->declares[0] instanceof Node\Stmt\DeclareDeclare
1✔
219
                                && $node->declares[0]->key->name === 'strict_types'
1✔
220
                                && $node->declares[0]->value instanceof Node\Scalar\LNumber
1✔
221
                        ) {
222
                                $phpFile->setStrictTypes((bool) $node->declares[0]->value->value);
1✔
223

224
                        } elseif ($node instanceof Node\Stmt\Namespace_) {
1✔
225
                                $namespaces[$node->name->toString()] = $node->stmts;
1✔
226
                        }
227
                }
228

229
                foreach ($namespaces as $name => $nodes) {
1✔
230
                        foreach ($nodes as $node) {
1✔
231
                                match (true) {
232
                                        $node instanceof Node\Stmt\Use_ => $this->addUseToNamespace($phpFile->addNamespace($name), $node),
1✔
233
                                        $node instanceof Node\Stmt\ClassLike => $this->addClassLikeToFile($phpFile, $node),
1✔
234
                                        $node instanceof Node\Stmt\Function_ => $this->addFunctionToFile($phpFile, $node),
1✔
235
                                        default => null,
1✔
236
                                };
237
                        }
238
                }
239

240
                return $phpFile;
1✔
241
        }
242

243

244
        private function addUseToNamespace(PhpNamespace $namespace, Node\Stmt\Use_ $node): void
1✔
245
        {
246
                $of = [
1✔
247
                        $node::TYPE_NORMAL => PhpNamespace::NameNormal,
1✔
248
                        $node::TYPE_FUNCTION => PhpNamespace::NameFunction,
1✔
249
                        $node::TYPE_CONSTANT => PhpNamespace::NameConstant,
1✔
250
                ][$node->type];
1✔
251
                foreach ($node->uses as $use) {
1✔
252
                        $namespace->addUse($use->name->toString(), $use->alias?->toString(), $of);
1✔
253
                }
254
        }
1✔
255

256

257
        private function addClassLikeToFile(PhpFile $phpFile, Node\Stmt\ClassLike $node): ClassLike
1✔
258
        {
259
                if ($node instanceof Node\Stmt\Class_) {
1✔
260
                        $class = $phpFile->addClass($node->namespacedName->toString());
1✔
261
                        $class->setFinal($node->isFinal());
1✔
262
                        $class->setAbstract($node->isAbstract());
1✔
263
                        $class->setReadOnly(method_exists($node, 'isReadonly') && $node->isReadonly());
1✔
264
                        if ($node->extends) {
1✔
265
                                $class->setExtends($node->extends->toString());
1✔
266
                        }
267
                        foreach ($node->implements as $item) {
1✔
268
                                $class->addImplement($item->toString());
1✔
269
                        }
270
                } elseif ($node instanceof Node\Stmt\Interface_) {
1✔
271
                        $class = $phpFile->addInterface($node->namespacedName->toString());
1✔
272
                        foreach ($node->extends as $item) {
1✔
273
                                $class->addExtend($item->toString());
1✔
274
                        }
275
                } elseif ($node instanceof Node\Stmt\Trait_) {
1✔
276
                        $class = $phpFile->addTrait($node->namespacedName->toString());
1✔
277

278
                } elseif ($node instanceof Node\Stmt\Enum_) {
1✔
279
                        $class = $phpFile->addEnum($node->namespacedName->toString());
1✔
280
                        $class->setType($node->scalarType?->toString());
1✔
281
                        foreach ($node->implements as $item) {
1✔
282
                                $class->addImplement($item->toString());
1✔
283
                        }
284
                }
285

286
                $this->addCommentAndAttributes($class, $node);
1✔
287
                $this->addClassMembers($class, $node);
1✔
288
                return $class;
1✔
289
        }
290

291

292
        private function addClassMembers(ClassLike $class, Node\Stmt\ClassLike $node): void
1✔
293
        {
294
                foreach ($node->stmts as $stmt) {
1✔
295
                        match (true) {
296
                                $stmt instanceof Node\Stmt\TraitUse => $this->addTraitToClass($class, $stmt),
1✔
297
                                $stmt instanceof Node\Stmt\Property => $this->addPropertyToClass($class, $stmt),
1✔
298
                                $stmt instanceof Node\Stmt\ClassMethod => $this->addMethodToClass($class, $stmt),
1✔
299
                                $stmt instanceof Node\Stmt\ClassConst => $this->addConstantToClass($class, $stmt),
1✔
300
                                $stmt instanceof Node\Stmt\EnumCase => $this->addEnumCaseToClass($class, $stmt),
1✔
UNCOV
301
                                default => null,
×
302
                        };
303
                }
304
        }
1✔
305

306

307
        private function addTraitToClass(ClassLike $class, Node\Stmt\TraitUse $node): void
1✔
308
        {
309
                foreach ($node->traits as $item) {
1✔
310
                        $trait = $class->addTrait($item->toString());
1✔
311
                }
312

313
                foreach ($node->adaptations as $item) {
1✔
314
                        $trait->addResolution(rtrim($this->getReformattedContents([$item], 0), ';'));
1✔
315
                }
316

317
                $this->addCommentAndAttributes($trait, $node);
1✔
318
        }
1✔
319

320

321
        private function addPropertyToClass(ClassLike $class, Node\Stmt\Property $node): void
1✔
322
        {
323
                foreach ($node->props as $item) {
1✔
324
                        $prop = $class->addProperty($item->name->toString());
1✔
325
                        $prop->setStatic($node->isStatic());
1✔
326
                        $prop->setVisibility($this->toVisibility($node->flags));
1✔
327
                        $prop->setType($node->type ? $this->toPhp($node->type) : null);
1✔
328
                        if ($item->default) {
1✔
329
                                $prop->setValue($this->toValue($item->default));
1✔
330
                        }
331

332
                        $prop->setReadOnly((method_exists($node, 'isReadonly') && $node->isReadonly()) || ($class instanceof ClassType && $class->isReadOnly()));
1✔
333
                        $this->addCommentAndAttributes($prop, $node);
1✔
334
                }
335
        }
1✔
336

337

338
        private function addMethodToClass(ClassLike $class, Node\Stmt\ClassMethod $node): void
1✔
339
        {
340
                $method = $class->addMethod($node->name->toString());
1✔
341
                $method->setAbstract($node->isAbstract());
1✔
342
                $method->setFinal($node->isFinal());
1✔
343
                $method->setStatic($node->isStatic());
1✔
344
                $method->setVisibility($this->toVisibility($node->flags));
1✔
345
                $this->setupFunction($method, $node);
1✔
346
                if ($method->getName() === Method::Constructor && $class instanceof ClassType && $class->isReadOnly()) {
1✔
347
                        array_map(fn($param) => $param instanceof PromotedParameter ? $param->setReadOnly() : $param, $method->getParameters());
1✔
348
                }
349
        }
1✔
350

351

352
        private function addConstantToClass(ClassLike $class, Node\Stmt\ClassConst $node): void
1✔
353
        {
354
                foreach ($node->consts as $item) {
1✔
355
                        $const = $class->addConstant($item->name->toString(), $this->toValue($item->value));
1✔
356
                        $const->setVisibility($this->toVisibility($node->flags));
1✔
357
                        $const->setFinal(method_exists($node, 'isFinal') && $node->isFinal());
1✔
358
                        $this->addCommentAndAttributes($const, $node);
1✔
359
                }
360
        }
1✔
361

362

363
        private function addEnumCaseToClass(EnumType $class, Node\Stmt\EnumCase $node): void
1✔
364
        {
365
                $value = match (true) {
1✔
366
                        $node->expr === null => null,
1✔
367
                        $node->expr instanceof Node\Scalar\LNumber, $node->expr instanceof Node\Scalar\String_ => $node->expr->value,
1✔
368
                        default => $this->toValue($node->expr),
1✔
369
                };
370
                $case = $class->addCase($node->name->toString(), $value);
1✔
371
                $this->addCommentAndAttributes($case, $node);
1✔
372
        }
1✔
373

374

375
        private function addFunctionToFile(PhpFile $phpFile, Node\Stmt\Function_ $node): void
1✔
376
        {
377
                $function = $phpFile->addFunction($node->namespacedName->toString());
1✔
378
                $this->setupFunction($function, $node);
1✔
379
        }
1✔
380

381

382
        private function addCommentAndAttributes(
1✔
383
                PhpFile|ClassLike|Constant|Property|GlobalFunction|Method|Parameter|EnumCase|TraitUse $element,
384
                Node $node,
385
        ): void
386
        {
387
                if ($node->getDocComment()) {
1✔
388
                        $comment = $node->getDocComment()->getReformattedText();
1✔
389
                        $comment = Helpers::unformatDocComment($comment);
1✔
390
                        $element->setComment($comment);
1✔
391
                        $node->setDocComment(new PhpParser\Comment\Doc(''));
1✔
392
                }
393

394
                foreach ($node->attrGroups ?? [] as $group) {
1✔
395
                        foreach ($group->attrs as $attribute) {
1✔
396
                                $args = [];
1✔
397
                                foreach ($attribute->args as $arg) {
1✔
398
                                        if ($arg->name) {
1✔
399
                                                $args[$arg->name->toString()] = $this->toValue($arg->value);
1✔
400
                                        } else {
401
                                                $args[] = $this->toValue($arg->value);
1✔
402
                                        }
403
                                }
404

405
                                $element->addAttribute($attribute->name->toString(), $args);
1✔
406
                        }
407
                }
408
        }
1✔
409

410

411
        private function setupFunction(GlobalFunction|Method $function, Node\FunctionLike $node): void
1✔
412
        {
413
                $function->setReturnReference($node->returnsByRef());
1✔
414
                $function->setReturnType($node->getReturnType() ? $this->toPhp($node->getReturnType()) : null);
1✔
415
                foreach ($node->getParams() as $item) {
1✔
416
                        $visibility = $this->toVisibility($item->flags);
1✔
417
                        $isReadonly = (bool) ($item->flags & Node\Stmt\Class_::MODIFIER_READONLY);
1✔
418
                        $param = $visibility
1✔
419
                                ? ($function->addPromotedParameter($item->var->name))->setVisibility($visibility)->setReadonly($isReadonly)
1✔
420
                                : $function->addParameter($item->var->name);
1✔
421
                        $param->setType($item->type ? $this->toPhp($item->type) : null);
1✔
422
                        $param->setReference($item->byRef);
1✔
423
                        $function->setVariadic($item->variadic);
1✔
424
                        if ($item->default) {
1✔
425
                                $param->setDefaultValue($this->toValue($item->default));
1✔
426
                        }
427

428
                        $this->addCommentAndAttributes($param, $item);
1✔
429
                }
430

431
                $this->addCommentAndAttributes($function, $node);
1✔
432
                if ($node->getStmts()) {
1✔
433
                        $indent = $function instanceof GlobalFunction ? 1 : 2;
1✔
434
                        $function->setBody($this->getReformattedContents($node->getStmts(), $indent));
1✔
435
                }
436
        }
1✔
437

438

439
        private function toValue(Node\Expr $node): mixed
1✔
440
        {
441
                if ($node instanceof Node\Expr\ConstFetch) {
1✔
442
                        return match ($node->name->toLowerString()) {
1✔
443
                                'null' => null,
1✔
444
                                'true' => true,
1✔
445
                                'false' => false,
1✔
446
                                default => new Literal($this->getReformattedContents([$node], 0)),
1✔
447
                        };
448
                } elseif ($node instanceof Node\Scalar\LNumber
1✔
449
                        || $node instanceof Node\Scalar\DNumber
1✔
450
                        || $node instanceof Node\Scalar\String_
1✔
451
                ) {
452
                        return $node->value;
1✔
453

454
                } elseif ($node instanceof Node\Expr\Array_) {
1✔
455
                        $res = [];
1✔
456
                        foreach ($node->items as $item) {
1✔
457
                                if ($item->unpack) {
1✔
458
                                        return new Literal($this->getReformattedContents([$node], 0));
1✔
459

460
                                } elseif ($item->key) {
1✔
461
                                        $key = $item->key instanceof Node\Identifier
1✔
UNCOV
462
                                                ? $item->key->name
×
463
                                                : $this->toValue($item->key);
1✔
464

465
                                        if ($key instanceof Literal) {
1✔
466
                                                return new Literal($this->getReformattedContents([$node], 0));
1✔
467
                                        }
468

469
                                        $res[$key] = $this->toValue($item->value);
1✔
470

471
                                } else {
472
                                        $res[] = $this->toValue($item->value);
1✔
473
                                }
474
                        }
475
                        return $res;
1✔
476

477
                } else {
478
                        return new Literal($this->getReformattedContents([$node], 0));
1✔
479
                }
480
        }
481

482

483
        private function toVisibility(int $flags): ?string
1✔
484
        {
485
                return match (true) {
486
                        (bool) ($flags & Node\Stmt\Class_::MODIFIER_PUBLIC) => ClassType::VisibilityPublic,
1✔
487
                        (bool) ($flags & Node\Stmt\Class_::MODIFIER_PROTECTED) => ClassType::VisibilityProtected,
1✔
488
                        (bool) ($flags & Node\Stmt\Class_::MODIFIER_PRIVATE) => ClassType::VisibilityPrivate,
1✔
489
                        default => null,
1✔
490
                };
491
        }
492

493

494
        private function toPhp(Node $value): string
1✔
495
        {
496
                $dolly = clone $value;
1✔
497
                $dolly->setAttribute('comments', []);
1✔
498
                return $this->printer->prettyPrint([$dolly]);
1✔
499
        }
500

501

502
        private function getNodeContents(Node ...$nodes): string
1✔
503
        {
504
                $start = $this->getNodeStartPos($nodes[0]);
1✔
505
                return substr($this->code, $start, end($nodes)->getEndFilePos() - $start + 1);
1✔
506
        }
507

508

509
        private function getNodeStartPos(Node $node): int
1✔
510
        {
511
                return ($comments = $node->getComments())
1✔
512
                        ? $comments[0]->getStartFilePos()
1✔
513
                        : $node->getStartFilePos();
1✔
514
        }
515
}
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

© 2025 Coveralls, Inc