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

nette / php-generator / 16784099881

06 Aug 2025 05:32PM UTC coverage: 92.006%. Remained the same
16784099881

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

98.78
/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\Modifiers;
15
use PhpParser\Node;
16
use PhpParser\NodeFinder;
17
use PhpParser\ParserFactory;
18
use function addcslashes, array_map, assert, class_exists, end, in_array, is_array, method_exists, rtrim, str_contains, str_repeat, str_replace, str_starts_with, strlen, substr, substr_replace, usort;
19

20

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

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

33

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

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

44

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

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

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

61

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

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

78
                return $res;
1✔
79
        }
80

81

82
        /** @return array<string, array<string, array{string, bool}>> */
83
        public function extractPropertyHookBodies(string $className): array
1✔
84
        {
85
                if (!class_exists(Node\PropertyHook::class)) {
1✔
86
                        return [];
×
87
                }
88

89
                $nodeFinder = new NodeFinder;
1✔
90
                $classNode = $nodeFinder->findFirst(
1✔
91
                        $this->statements,
1✔
92
                        fn(Node $node) => $node instanceof Node\Stmt\ClassLike && $node->namespacedName->toString() === $className,
1✔
93
                );
94

95
                $res = [];
1✔
96
                foreach ($nodeFinder->findInstanceOf($classNode, Node\Stmt\Property::class) as $propertyNode) {
1✔
97
                        foreach ($propertyNode->props as $propNode) {
1✔
98
                                $propName = $propNode->name->toString();
1✔
99
                                foreach ($propertyNode->hooks as $hookNode) {
1✔
100
                                        $body = $hookNode->body;
1✔
101
                                        if ($body !== null) {
1✔
102
                                                $contents = $this->getReformattedContents(is_array($body) ? $body : [$body], 3);
1✔
103
                                                $res[$propName][$hookNode->name->toString()] = [$contents, !is_array($body)];
1✔
104
                                        }
105
                                }
106
                        }
107
                }
108
                return $res;
1✔
109
        }
110

111

112
        public function extractFunctionBody(string $name): string
1✔
113
        {
114
                $functionNode = (new NodeFinder)->findFirst(
1✔
115
                        $this->statements,
1✔
116
                        fn(Node $node) => $node instanceof Node\Stmt\Function_ && $node->namespacedName->toString() === $name,
1✔
117
                );
118
                assert($functionNode instanceof Node\Stmt\Function_);
119

120
                return $this->getReformattedContents($functionNode->stmts, 1);
1✔
121
        }
122

123

124
        /** @param  Node[]  $nodes */
125
        private function getReformattedContents(array $nodes, int $level): string
1✔
126
        {
127
                if (!$nodes) {
1✔
128
                        return '';
1✔
129
                }
130
                $body = $this->getNodeContents(...$nodes);
1✔
131
                $body = $this->performReplacements($body, $this->prepareReplacements($nodes, $level));
1✔
132
                return Helpers::unindent($body, $level);
1✔
133
        }
134

135

136
        /**
137
         * @param  Node[]  $nodes
138
         * @return array<array{int, int, string}>
139
         */
140
        private function prepareReplacements(array $nodes, int $level): array
1✔
141
        {
142
                $start = $this->getNodeStartPos($nodes[0]);
1✔
143
                $replacements = [];
1✔
144
                $indent = "\n" . str_repeat("\t", $level);
1✔
145
                (new NodeFinder)->find($nodes, function (Node $node) use (&$replacements, $start, $level, $indent) {
1✔
146
                        if ($node instanceof Node\Name\FullyQualified) {
1✔
147
                                if ($node->getAttribute('originalName') instanceof Node\Name) {
1✔
148
                                        $of = match (true) {
1✔
149
                                                $node->getAttribute('parent') instanceof Node\Expr\ConstFetch => PhpNamespace::NameConstant,
1✔
150
                                                $node->getAttribute('parent') instanceof Node\Expr\FuncCall => PhpNamespace::NameFunction,
1✔
151
                                                default => PhpNamespace::NameNormal,
1✔
152
                                        };
153
                                        $replacements[] = [
1✔
154
                                                $node->getStartFilePos() - $start,
1✔
155
                                                $node->getEndFilePos() - $start,
1✔
156
                                                Helpers::tagName($node->toCodeString(), $of),
1✔
157
                                        ];
158
                                }
159

160
                        } elseif (
161
                                $node instanceof Node\Scalar\String_
1✔
162
                                && in_array($node->getAttribute('kind'), [Node\Scalar\String_::KIND_SINGLE_QUOTED, Node\Scalar\String_::KIND_DOUBLE_QUOTED], true)
1✔
163
                                && str_contains($node->getAttribute('rawValue'), "\n")
1✔
164
                        ) { // multi-line strings -> single line
165
                                $replacements[] = [
1✔
166
                                        $node->getStartFilePos() - $start,
1✔
167
                                        $node->getEndFilePos() - $start,
1✔
168
                                        '"' . addcslashes($node->value, "\x00..\x1F\"") . '"',
1✔
169
                                ];
170

171
                        } elseif (
172
                                $node instanceof Node\Scalar\String_
1✔
173
                                && in_array($node->getAttribute('kind'), [Node\Scalar\String_::KIND_NOWDOC, Node\Scalar\String_::KIND_HEREDOC], true)
1✔
174
                                && Helpers::unindent($node->getAttribute('docIndentation'), $level) === $node->getAttribute('docIndentation')
1✔
175
                        ) { // fix indentation of NOWDOW/HEREDOC
176
                                $replacements[] = [
1✔
177
                                        $node->getStartFilePos() - $start,
1✔
178
                                        $node->getEndFilePos() - $start,
1✔
179
                                        str_replace("\n", $indent, $this->getNodeContents($node)),
1✔
180
                                ];
181

182
                        } elseif (
183
                                $node instanceof Node\Scalar\Encapsed
1✔
184
                                && $node->getAttribute('kind') === Node\Scalar\String_::KIND_DOUBLE_QUOTED
1✔
185
                        ) { // multi-line strings -> single line
186
                                foreach ($node->parts as $part) {
1✔
187
                                        if ($part instanceof Node\Scalar\EncapsedStringPart) {
1✔
188
                                                $replacements[] = [
1✔
189
                                                        $part->getStartFilePos() - $start,
1✔
190
                                                        $part->getEndFilePos() - $start,
1✔
191
                                                        addcslashes($part->value, "\x00..\x1F\""),
1✔
192
                                                ];
193
                                        }
194
                                }
195
                        } elseif (
196
                                $node instanceof Node\Scalar\Encapsed && $node->getAttribute('kind') === Node\Scalar\String_::KIND_HEREDOC
1✔
197
                                && Helpers::unindent($node->getAttribute('docIndentation'), $level) === $node->getAttribute('docIndentation')
1✔
198
                        ) { // fix indentation of HEREDOC
199
                                $replacements[] = [
1✔
200
                                        $tmp = $node->getStartFilePos() - $start + strlen($node->getAttribute('docLabel')) + 3, // <<<
1✔
201
                                        $tmp,
1✔
202
                                        $indent,
1✔
203
                                ];
204
                                $replacements[] = [
1✔
205
                                        $tmp = $node->getEndFilePos() - $start - strlen($node->getAttribute('docLabel')),
1✔
206
                                        $tmp,
1✔
207
                                        $indent,
1✔
208
                                ];
209
                                foreach ($node->parts as $part) {
1✔
210
                                        if ($part instanceof Node\Scalar\EncapsedStringPart) {
1✔
211
                                                $replacements[] = [
1✔
212
                                                        $part->getStartFilePos() - $start,
1✔
213
                                                        $part->getEndFilePos() - $start,
1✔
214
                                                        str_replace("\n", $indent, $this->getNodeContents($part)),
1✔
215
                                                ];
216
                                        }
217
                                }
218
                        }
219
                });
1✔
220
                return $replacements;
1✔
221
        }
222

223

224
        /** @param  array<array{int, int, string}>  $replacements */
225
        private function performReplacements(string $s, array $replacements): string
1✔
226
        {
227
                usort($replacements, fn($a, $b) => $b[0] <=> $a[0]);
1✔
228

229
                foreach ($replacements as [$start, $end, $replacement]) {
1✔
230
                        $s = substr_replace($s, $replacement, $start, $end - $start + 1);
1✔
231
                }
232

233
                return $s;
1✔
234
        }
235

236

237
        public function extractAll(): PhpFile
238
        {
239
                $phpFile = new PhpFile;
1✔
240

241
                if (
242
                        $this->statements
1✔
243
                        && !$this->statements[0] instanceof Node\Stmt\ClassLike
1✔
244
                        && !$this->statements[0] instanceof Node\Stmt\Function_
1✔
245
                ) {
246
                        $this->addCommentAndAttributes($phpFile, $this->statements[0]);
1✔
247
                }
248

249
                $namespaces = ['' => $this->statements];
1✔
250
                foreach ($this->statements as $node) {
1✔
251
                        if ($node instanceof Node\Stmt\Declare_
1✔
252
                                && $node->declares[0]->key->name === 'strict_types'
1✔
253
                                && $node->declares[0]->value instanceof Node\Scalar\LNumber
1✔
254
                        ) {
255
                                $phpFile->setStrictTypes((bool) $node->declares[0]->value->value);
1✔
256

257
                        } elseif ($node instanceof Node\Stmt\Namespace_) {
1✔
258
                                $namespaces[$node->name->toString()] = $node->stmts;
1✔
259
                        }
260
                }
261

262
                foreach ($namespaces as $name => $nodes) {
1✔
263
                        foreach ($nodes as $node) {
1✔
264
                                match (true) {
265
                                        $node instanceof Node\Stmt\Use_ => $this->addUseToNamespace($phpFile->addNamespace($name), $node),
1✔
266
                                        $node instanceof Node\Stmt\ClassLike => $this->addClassLikeToFile($phpFile, $node),
1✔
267
                                        $node instanceof Node\Stmt\Function_ => $this->addFunctionToFile($phpFile, $node),
1✔
268
                                        default => null,
1✔
269
                                };
270
                        }
271
                }
272

273
                return $phpFile;
1✔
274
        }
275

276

277
        private function addUseToNamespace(PhpNamespace $namespace, Node\Stmt\Use_ $node): void
1✔
278
        {
279
                $of = [
1✔
280
                        $node::TYPE_NORMAL => PhpNamespace::NameNormal,
1✔
281
                        $node::TYPE_FUNCTION => PhpNamespace::NameFunction,
1✔
282
                        $node::TYPE_CONSTANT => PhpNamespace::NameConstant,
1✔
283
                ][$node->type];
1✔
284
                foreach ($node->uses as $use) {
1✔
285
                        $namespace->addUse($use->name->toString(), $use->alias?->toString(), $of);
1✔
286
                }
287
        }
1✔
288

289

290
        private function addClassLikeToFile(PhpFile $phpFile, Node\Stmt\ClassLike $node): ClassLike
1✔
291
        {
292
                if ($node instanceof Node\Stmt\Class_) {
1✔
293
                        $class = $phpFile->addClass($node->namespacedName->toString());
1✔
294
                        $class->setFinal($node->isFinal());
1✔
295
                        $class->setAbstract($node->isAbstract());
1✔
296
                        $class->setReadOnly(method_exists($node, 'isReadonly') && $node->isReadonly());
1✔
297
                        if ($node->extends) {
1✔
298
                                $class->setExtends($node->extends->toString());
1✔
299
                        }
300
                        foreach ($node->implements as $item) {
1✔
301
                                $class->addImplement($item->toString());
1✔
302
                        }
303
                } elseif ($node instanceof Node\Stmt\Interface_) {
1✔
304
                        $class = $phpFile->addInterface($node->namespacedName->toString());
1✔
305
                        foreach ($node->extends as $item) {
1✔
306
                                $class->addExtend($item->toString());
1✔
307
                        }
308
                } elseif ($node instanceof Node\Stmt\Trait_) {
1✔
309
                        $class = $phpFile->addTrait($node->namespacedName->toString());
1✔
310

311
                } elseif ($node instanceof Node\Stmt\Enum_) {
1✔
312
                        $class = $phpFile->addEnum($node->namespacedName->toString());
1✔
313
                        $class->setType($node->scalarType?->toString());
1✔
314
                        foreach ($node->implements as $item) {
1✔
315
                                $class->addImplement($item->toString());
1✔
316
                        }
317
                }
318

319
                $this->addCommentAndAttributes($class, $node);
1✔
320
                $this->addClassMembers($class, $node);
1✔
321
                return $class;
1✔
322
        }
323

324

325
        private function addClassMembers(ClassLike $class, Node\Stmt\ClassLike $node): void
1✔
326
        {
327
                foreach ($node->stmts as $stmt) {
1✔
328
                        match (true) {
329
                                $stmt instanceof Node\Stmt\TraitUse => $this->addTraitToClass($class, $stmt),
1✔
330
                                $stmt instanceof Node\Stmt\Property => $this->addPropertyToClass($class, $stmt),
1✔
331
                                $stmt instanceof Node\Stmt\ClassMethod => $this->addMethodToClass($class, $stmt),
1✔
332
                                $stmt instanceof Node\Stmt\ClassConst => $this->addConstantToClass($class, $stmt),
1✔
333
                                $stmt instanceof Node\Stmt\EnumCase => $this->addEnumCaseToClass($class, $stmt),
1✔
334
                                default => null,
×
335
                        };
336
                }
337
        }
1✔
338

339

340
        private function addTraitToClass(ClassLike $class, Node\Stmt\TraitUse $node): void
1✔
341
        {
342
                foreach ($node->traits as $item) {
1✔
343
                        $trait = $class->addTrait($item->toString());
1✔
344
                }
345
                assert($trait instanceof TraitUse);
346

347
                foreach ($node->adaptations as $item) {
1✔
348
                        $trait->addResolution(rtrim($this->getReformattedContents([$item], 0), ';'));
1✔
349
                }
350

351
                $this->addCommentAndAttributes($trait, $node);
1✔
352
        }
1✔
353

354

355
        private function addPropertyToClass(ClassLike $class, Node\Stmt\Property $node): void
1✔
356
        {
357
                foreach ($node->props as $item) {
1✔
358
                        $prop = $class->addProperty($item->name->toString());
1✔
359
                        $prop->setStatic($node->isStatic());
1✔
360
                        $prop->setVisibility($this->toVisibility($node->flags), $this->toSetterVisibility($node->flags));
1✔
361
                        $prop->setType($node->type ? $this->toPhp($node->type) : null);
1✔
362
                        if ($item->default) {
1✔
363
                                $prop->setValue($this->toValue($item->default));
1✔
364
                        }
365

366
                        $prop->setReadOnly((method_exists($node, 'isReadonly') && $node->isReadonly()) || ($class instanceof ClassType && $class->isReadOnly()));
1✔
367
                        $this->addCommentAndAttributes($prop, $node);
1✔
368

369
                        $prop->setAbstract((bool) ($node->flags & Node\Stmt\Class_::MODIFIER_ABSTRACT));
1✔
370
                        $prop->setFinal((bool) ($node->flags & Node\Stmt\Class_::MODIFIER_FINAL));
1✔
371
                        $this->addHooksToProperty($prop, $node);
1✔
372
                }
373
        }
1✔
374

375

376
        private function addHooksToProperty(Property|PromotedParameter $prop, Node\Stmt\Property|Node\Param $node): void
1✔
377
        {
378
                if (!class_exists(Node\PropertyHook::class)) {
1✔
379
                        return;
×
380
                }
381

382
                foreach ($node->hooks as $hookNode) {
1✔
383
                        $hook = $prop->addHook($hookNode->name->toString());
1✔
384
                        $hook->setFinal((bool) ($hookNode->flags & Modifiers::FINAL));
1✔
385
                        $this->setupFunction($hook, $hookNode);
1✔
386
                        if ($hookNode->body === null) {
1✔
387
                                $hook->setAbstract();
1✔
388
                        } elseif (!is_array($hookNode->body)) {
1✔
389
                                $hook->setBody($this->getReformattedContents([$hookNode->body], 1), short: true);
1✔
390
                        }
391
                }
392
        }
1✔
393

394

395
        private function addMethodToClass(ClassLike $class, Node\Stmt\ClassMethod $node): void
1✔
396
        {
397
                $method = $class->addMethod($node->name->toString());
1✔
398
                $method->setAbstract($node->isAbstract());
1✔
399
                $method->setFinal($node->isFinal());
1✔
400
                $method->setStatic($node->isStatic());
1✔
401
                $method->setVisibility($this->toVisibility($node->flags));
1✔
402
                $this->setupFunction($method, $node);
1✔
403
                if ($method->getName() === Method::Constructor && $class instanceof ClassType && $class->isReadOnly()) {
1✔
404
                        array_map(fn($param) => $param instanceof PromotedParameter ? $param->setReadOnly() : $param, $method->getParameters());
1✔
405
                }
406
        }
1✔
407

408

409
        private function addConstantToClass(ClassLike $class, Node\Stmt\ClassConst $node): void
1✔
410
        {
411
                foreach ($node->consts as $item) {
1✔
412
                        $const = $class->addConstant($item->name->toString(), $this->toValue($item->value));
1✔
413
                        $const->setVisibility($this->toVisibility($node->flags));
1✔
414
                        $const->setFinal(method_exists($node, 'isFinal') && $node->isFinal());
1✔
415
                        $this->addCommentAndAttributes($const, $node);
1✔
416
                }
417
        }
1✔
418

419

420
        private function addEnumCaseToClass(EnumType $class, Node\Stmt\EnumCase $node): void
1✔
421
        {
422
                $value = match (true) {
1✔
423
                        $node->expr === null => null,
1✔
424
                        $node->expr instanceof Node\Scalar\LNumber, $node->expr instanceof Node\Scalar\String_ => $node->expr->value,
1✔
425
                        default => $this->toValue($node->expr),
1✔
426
                };
427
                $case = $class->addCase($node->name->toString(), $value);
1✔
428
                $this->addCommentAndAttributes($case, $node);
1✔
429
        }
1✔
430

431

432
        private function addFunctionToFile(PhpFile $phpFile, Node\Stmt\Function_ $node): void
1✔
433
        {
434
                $function = $phpFile->addFunction($node->namespacedName->toString());
1✔
435
                $this->setupFunction($function, $node);
1✔
436
        }
1✔
437

438

439
        private function addCommentAndAttributes(
1✔
440
                PhpFile|ClassLike|Constant|Property|GlobalFunction|Method|Parameter|EnumCase|TraitUse|PropertyHook $element,
441
                Node $node,
442
        ): void
443
        {
444
                if ($node->getDocComment()) {
1✔
445
                        $comment = $node->getDocComment()->getReformattedText();
1✔
446
                        $comment = Helpers::unformatDocComment($comment);
1✔
447
                        $element->setComment($comment);
1✔
448
                        $node->setDocComment(new PhpParser\Comment\Doc(''));
1✔
449
                }
450

451
                foreach ($node->attrGroups ?? [] as $group) {
1✔
452
                        foreach ($group->attrs as $attribute) {
1✔
453
                                $args = [];
1✔
454
                                foreach ($attribute->args as $arg) {
1✔
455
                                        if ($arg->name) {
1✔
456
                                                $args[$arg->name->toString()] = $this->toValue($arg->value);
1✔
457
                                        } else {
458
                                                $args[] = $this->toValue($arg->value);
1✔
459
                                        }
460
                                }
461

462
                                $element->addAttribute($attribute->name->toString(), $args);
1✔
463
                        }
464
                }
465
        }
1✔
466

467

468
        private function setupFunction(GlobalFunction|Method|PropertyHook $function, Node\FunctionLike $node): void
1✔
469
        {
470
                $function->setReturnReference($node->returnsByRef());
1✔
471
                if (!$function instanceof PropertyHook) {
1✔
472
                        $function->setReturnType($node->getReturnType() ? $this->toPhp($node->getReturnType()) : null);
1✔
473
                }
474

475
                foreach ($node->getParams() as $item) {
1✔
476
                        $getVisibility = $this->toVisibility($item->flags);
1✔
477
                        $setVisibility = $this->toSetterVisibility($item->flags);
1✔
478
                        $final = (bool) ($item->flags & Modifiers::FINAL);
1✔
479
                        if ($getVisibility || $setVisibility || $final) {
1✔
480
                                $param = $function->addPromotedParameter($item->var->name)
1✔
481
                                        ->setVisibility($getVisibility, $setVisibility)
1✔
482
                                        ->setReadonly((bool) ($item->flags & Node\Stmt\Class_::MODIFIER_READONLY))
1✔
483
                                        ->setFinal($final);
1✔
484
                                $this->addHooksToProperty($param, $item);
1✔
485
                        } else {
486
                                $param = $function->addParameter($item->var->name);
1✔
487
                        }
488
                        $param->setType($item->type ? $this->toPhp($item->type) : null);
1✔
489
                        $param->setReference($item->byRef);
1✔
490
                        if (!$function instanceof PropertyHook) {
1✔
491
                                $function->setVariadic($item->variadic);
1✔
492
                        }
493
                        if ($item->default) {
1✔
494
                                $param->setDefaultValue($this->toValue($item->default));
1✔
495
                        }
496

497
                        $this->addCommentAndAttributes($param, $item);
1✔
498
                }
499

500
                $this->addCommentAndAttributes($function, $node);
1✔
501
                if ($node->getStmts()) {
1✔
502
                        $indent = $function instanceof GlobalFunction ? 1 : 2;
1✔
503
                        $function->setBody($this->getReformattedContents($node->getStmts(), $indent));
1✔
504
                }
505
        }
1✔
506

507

508
        private function toValue(Node\Expr $node): mixed
1✔
509
        {
510
                if ($node instanceof Node\Expr\ConstFetch) {
1✔
511
                        return match ($node->name->toLowerString()) {
1✔
512
                                'null' => null,
1✔
513
                                'true' => true,
1✔
514
                                'false' => false,
1✔
515
                                default => new Literal($this->getReformattedContents([$node], 0)),
1✔
516
                        };
517
                } elseif ($node instanceof Node\Scalar\LNumber
1✔
518
                        || $node instanceof Node\Scalar\DNumber
1✔
519
                        || $node instanceof Node\Scalar\String_
1✔
520
                ) {
521
                        return $node->value;
1✔
522

523
                } elseif ($node instanceof Node\Expr\Array_) {
1✔
524
                        $res = [];
1✔
525
                        foreach ($node->items as $item) {
1✔
526
                                if ($item->unpack) {
1✔
527
                                        return new Literal($this->getReformattedContents([$node], 0));
1✔
528

529
                                } elseif ($item->key) {
1✔
530
                                        $key = $this->toValue($item->key);
1✔
531
                                        if ($key instanceof Literal) {
1✔
532
                                                return new Literal($this->getReformattedContents([$node], 0));
1✔
533
                                        }
534

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

537
                                } else {
538
                                        $res[] = $this->toValue($item->value);
1✔
539
                                }
540
                        }
541
                        return $res;
1✔
542

543
                } else {
544
                        return new Literal($this->getReformattedContents([$node], 0));
1✔
545
                }
546
        }
547

548

549
        private function toVisibility(int $flags): ?string
1✔
550
        {
551
                return match (true) {
552
                        (bool) ($flags & Node\Stmt\Class_::MODIFIER_PUBLIC) => Visibility::Public,
1✔
553
                        (bool) ($flags & Node\Stmt\Class_::MODIFIER_PROTECTED) => Visibility::Protected,
1✔
554
                        (bool) ($flags & Node\Stmt\Class_::MODIFIER_PRIVATE) => Visibility::Private,
1✔
555
                        default => null,
1✔
556
                };
557
        }
558

559

560
        private function toSetterVisibility(int $flags): ?string
1✔
561
        {
562
                return match (true) {
563
                        !class_exists(Node\PropertyHook::class) => null,
1✔
564
                        (bool) ($flags & Modifiers::PUBLIC_SET) => Visibility::Public,
1✔
565
                        (bool) ($flags & Modifiers::PROTECTED_SET) => Visibility::Protected,
1✔
566
                        (bool) ($flags & Modifiers::PRIVATE_SET) => Visibility::Private,
1✔
567
                        default => null,
1✔
568
                };
569
        }
570

571

572
        private function toPhp(Node $value): string
1✔
573
        {
574
                $dolly = clone $value;
1✔
575
                $dolly->setAttribute('comments', []);
1✔
576
                return $this->printer->prettyPrint([$dolly]);
1✔
577
        }
578

579

580
        private function getNodeContents(Node ...$nodes): string
1✔
581
        {
582
                $start = $this->getNodeStartPos($nodes[0]);
1✔
583
                return substr($this->code, $start, end($nodes)->getEndFilePos() - $start + 1);
1✔
584
        }
585

586

587
        private function getNodeStartPos(Node $node): int
1✔
588
        {
589
                return ($comments = $node->getComments())
1✔
590
                        ? $comments[0]->getStartFilePos()
1✔
591
                        : $node->getStartFilePos();
1✔
592
        }
593
}
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