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

voku / Simple-PHP-Code-Parser / 24275016806

11 Apr 2026 04:49AM UTC coverage: 82.946% (+0.09%) from 82.857%
24275016806

Pull #79

github

web-flow
Merge 6a49d9ec5 into 3fcaa1a81
Pull Request #79: Fix PHP 8 type resolution order and safe autoloading for newer syntax

42 of 102 new or added lines in 9 files covered. (41.18%)

79 existing lines in 6 files now uncovered.

1571 of 1894 relevant lines covered (82.95%)

44.9 hits per line

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

87.11
/src/voku/SimplePhpParser/Parsers/PhpCodeParser.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace voku\SimplePhpParser\Parsers;
6

7
use FilesystemIterator;
8
use PhpParser\NodeTraverser;
9
use PhpParser\NodeVisitor\NameResolver;
10
use PhpParser\ParserFactory;
11
use React\Filesystem\Node\FileInterface;
12
use React\Filesystem\Node\NodeInterface;
13
use RecursiveDirectoryIterator;
14
use RecursiveIteratorIterator;
15
use SplFileInfo;
16
use voku\cache\Cache;
17
use voku\SimplePhpParser\Model\PHPInterface;
18
use voku\SimplePhpParser\Parsers\Helper\ParserContainer;
19
use voku\SimplePhpParser\Parsers\Helper\ParserErrorHandler;
20
use voku\SimplePhpParser\Parsers\Helper\Utils;
21
use voku\SimplePhpParser\Parsers\Visitors\ASTVisitor;
22
use voku\SimplePhpParser\Parsers\Visitors\ParentConnector;
23
use function React\Async\await;
24
use function React\Promise\all;
25

26
final class PhpCodeParser
27
{
28
    /**
29
     * @internal
30
     */
31
    private const CACHE_KEY_HELPER = 'simple-php-code-parser-v6-';
32

33
    /**
34
     * @param string   $code
35
     * @param string[] $autoloaderProjectPaths
36
     *
37
     * @return \voku\SimplePhpParser\Parsers\Helper\ParserContainer
38
     */
39
    public static function getFromString(
40
        string $code,
41
        array $autoloaderProjectPaths = []
42
    ): ParserContainer {
43
        return self::getPhpFiles(
38✔
44
            $code,
38✔
45
            $autoloaderProjectPaths
38✔
46
        );
38✔
47
    }
48

49
    /**
50
     * @param string   $className
51
     * @param string[] $autoloaderProjectPaths
52
     *
53
     * @phpstan-param class-string $className
54
     *
55
     * @return \voku\SimplePhpParser\Parsers\Helper\ParserContainer
56
     */
57
    public static function getFromClassName(
58
        string $className,
59
        array $autoloaderProjectPaths = []
60
    ): ParserContainer {
61
        $reflectionClass = Utils::createClassReflectionInstance($className);
4✔
62

63
        return self::getPhpFiles(
4✔
64
            (string) $reflectionClass->getFileName(),
4✔
65
            $autoloaderProjectPaths
4✔
66
        );
4✔
67
    }
68

69
    /**
70
     * @param string   $pathOrCode
71
     * @param string[] $autoloaderProjectPaths
72
     * @param string[] $pathExcludeRegex
73
     * @param string[] $fileExtensions
74
     *
75
     * @return \voku\SimplePhpParser\Parsers\Helper\ParserContainer
76
     */
77
    public static function getPhpFiles(
78
        string $pathOrCode,
79
        array $autoloaderProjectPaths = [],
80
        array $pathExcludeRegex = [],
81
        array $fileExtensions = []
82
    ): ParserContainer {
83
        // Push a disposable handler so restore_error_handler() below will only
84
        // pop this one entry, leaving any pre-existing handlers (e.g. PHPUnit's)
85
        // intact on the stack.
86
        \set_error_handler(null);
156✔
87
        try {
88
            foreach ($autoloaderProjectPaths as $projectPath) {
156✔
89
                if (\file_exists($projectPath) && \is_file($projectPath)) {
×
90
                    require_once $projectPath;
×
91
                } elseif (\file_exists($projectPath . '/vendor/autoload.php')) {
×
92
                    require_once $projectPath . '/vendor/autoload.php';
×
93
                } elseif (\file_exists($projectPath . '/../vendor/autoload.php')) {
×
94
                    require_once $projectPath . '/../vendor/autoload.php';
×
95
                }
96
            }
97
        } finally {
98
            \restore_error_handler();
156✔
99
        }
100

101
        $phpCodes = self::getCode(
156✔
102
            $pathOrCode,
156✔
103
            $pathExcludeRegex,
156✔
104
            $fileExtensions
156✔
105
        );
156✔
106

107
        $parserContainer = new ParserContainer();
156✔
108
        $visitor = new ASTVisitor($parserContainer);
156✔
109

110
        $processResults = [];
156✔
111
        $phpCodesChunks = \array_chunk($phpCodes, Utils::getCpuCores(), true);
156✔
112

113
        foreach ($phpCodesChunks as $phpCodesChunk) {
156✔
114
            foreach ($phpCodesChunk as $codeAndFileName) {
156✔
115
                $processResults[] = self::process(
156✔
116
                    $codeAndFileName['content'],
156✔
117
                    $codeAndFileName['fileName'],
156✔
118
                    $parserContainer,
156✔
119
                    $visitor
156✔
120
                );
156✔
121
            }
122
        }
123

124
        foreach ($processResults as $response) {
156✔
125
            if ($response instanceof ParserContainer) {
156✔
126
                $parserContainer->setTraits($response->getTraits());
156✔
127
                $parserContainer->setClasses($response->getClasses());
156✔
128
                $parserContainer->setInterfaces($response->getInterfaces());
156✔
129
                $parserContainer->setEnums($response->getEnums());
156✔
130
                $parserContainer->setConstants($response->getConstants());
156✔
131
                $parserContainer->setFunctions($response->getFunctions());
156✔
132
            } elseif ($response instanceof ParserErrorHandler) {
×
133
                $parserContainer->setParseError($response);
×
134
            }
135
        }
136

137
        $interfaces = $parserContainer->getInterfaces();
156✔
138
        foreach ($interfaces as &$interface) {
156✔
139
            $interface->parentInterfaces = $visitor->combineParentInterfaces($interface);
8✔
140
        }
141
        unset($interface);
156✔
142

143
        $pathTmp = null;
156✔
144
        if (\is_file($pathOrCode)) {
156✔
145
            $pathTmp = \realpath(\pathinfo($pathOrCode, \PATHINFO_DIRNAME));
110✔
146
        } elseif (\is_dir($pathOrCode)) {
46✔
147
            $pathTmp = \realpath($pathOrCode);
8✔
148
        }
149

150
        $classesTmp = &$parserContainer->getClassesByReference();
156✔
151
        foreach ($classesTmp as &$classTmp) {
156✔
152
            $classTmp->interfaces = Utils::flattenArray(
121✔
153
                $visitor->combineImplementedInterfaces($classTmp),
121✔
154
                false
121✔
155
            );
121✔
156

157
            self::mergeInheritdocData(
121✔
158
                $classTmp,
121✔
159
                $classesTmp,
121✔
160
                $interfaces,
121✔
161
                $parserContainer
121✔
162
            );
121✔
163
        }
164
        unset($classTmp);
156✔
165

166
        // remove properties / methods / classes from outside of the current file-path-scope
167
        if ($pathTmp) {
156✔
168
            $classesTmp2 = &$parserContainer->getClassesByReference();
118✔
169
            foreach ($classesTmp2 as $classKey => $classTmp2) {
118✔
170
                foreach ($classTmp2->constants as $constantKey => $constant) {
99✔
171
                    if ($constant->file && \strpos($constant->file, $pathTmp) === false) {
54✔
172
                        unset($classTmp2->constants[$constantKey]);
6✔
173
                    }
174
                }
175

176
                foreach ($classTmp2->properties as $propertyKey => $property) {
99✔
177
                    if ($property->file && \strpos($property->file, $pathTmp) === false) {
85✔
178
                        unset($classTmp2->properties[$propertyKey]);
8✔
179
                    }
180
                }
181

182
                foreach ($classTmp2->methods as $methodKey => $method) {
99✔
183
                    if ($method->file && \strpos($method->file, $pathTmp) === false) {
97✔
184
                        unset($classTmp2->methods[$methodKey]);
8✔
185
                    }
186
                }
187

188
                if ($classTmp2->file && \strpos($classTmp2->file, $pathTmp) === false) {
99✔
189
                    unset($classesTmp2[$classKey]);
8✔
190
                }
191
            }
192
        }
193

194
        return $parserContainer;
156✔
195
    }
196

197
    /**
198
     * @param string                                               $phpCode
199
     * @param string|null                                          $fileName
200
     * @param \voku\SimplePhpParser\Parsers\Helper\ParserContainer $parserContainer
201
     * @param \voku\SimplePhpParser\Parsers\Visitors\ASTVisitor    $visitor
202
     *
203
     * @return \voku\SimplePhpParser\Parsers\Helper\ParserContainer|\voku\SimplePhpParser\Parsers\Helper\ParserErrorHandler
204
     */
205
    public static function process(
206
        string $phpCode,
207
        ?string $fileName,
208
        ParserContainer $parserContainer,
209
        ASTVisitor $visitor
210
    ) {
211
        $parser = (new ParserFactory())->createForNewestSupportedVersion();
156✔
212

213
        $errorHandler = new ParserErrorHandler();
156✔
214

215
        $nameResolver = new NameResolver(
156✔
216
            $errorHandler,
156✔
217
            [
156✔
218
                'preserveOriginalNames' => true,
156✔
219
            ]
156✔
220
        );
156✔
221

222
        /** @var \PhpParser\Node[]|null $parsedCode */
223
        $parsedCode = $parser->parse($phpCode, $errorHandler);
156✔
224

225
        if ($parsedCode === null) {
156✔
226
            return $errorHandler;
×
227
        }
228

229
        // Pass 1: set parent attributes and fully resolve all names in the AST.
230
        // NameResolver modifies Name nodes in-place (converting them to FullyQualified),
231
        // so by the time ASTVisitor runs in pass 2, every type-hint Name node already
232
        // carries its fully-qualified form. This is necessary because ASTVisitor processes
233
        // class members (properties, methods) eagerly inside enterNode(Class_), before
234
        // the single-pass traverser would have had a chance to visit those child nodes.
235
        $traverser1 = new NodeTraverser();
156✔
236
        $traverser1->addVisitor(new ParentConnector());
156✔
237
        $traverser1->addVisitor($nameResolver);
156✔
238
        $traverser1->traverse($parsedCode);
156✔
239

240
        $visitor->fileName = $fileName;
156✔
241

242
        // Pass 2: extract model objects from the already-resolved AST.
243
        $traverser2 = new NodeTraverser();
156✔
244
        $traverser2->addVisitor($visitor);
156✔
245
        $traverser2->traverse($parsedCode);
156✔
246

247
        return $parserContainer;
156✔
248
    }
249

250
    /**
251
     * @param string   $pathOrCode
252
     * @param string[] $pathExcludeRegex
253
     * @param string[] $fileExtensions
254
     *
255
     * @return array
256
     *
257
     * @psalm-return array<string, array{content: string, fileName: null|string}>
258
     */
259
    private static function getCode(
260
        string $pathOrCode,
261
        array $pathExcludeRegex = [],
262
        array $fileExtensions = []
263
    ): array {
264
        // init
265
        $phpCodes = [];
156✔
266
        /** @var SplFileInfo[] $phpFileIterators */
267
        $phpFileIterators = [];
156✔
268
        /** @var list<\React\Promise\PromiseInterface<array{content: \React\Promise\PromiseInterface<string>, fileName: string, cacheKey: string}>> $phpFilePromises */
269
        $phpFilePromises = [];
156✔
270

271
        // fallback
272
        if (\count($fileExtensions) === 0) {
156✔
273
            $fileExtensions = ['.php'];
156✔
274
        }
275

276
        if (\is_file($pathOrCode)) {
156✔
277
            $phpFileIterators = [new SplFileInfo($pathOrCode)];
110✔
278
        } elseif (\is_dir($pathOrCode)) {
46✔
279
            $phpFileIterators = new RecursiveIteratorIterator(
8✔
280
                new RecursiveDirectoryIterator($pathOrCode, FilesystemIterator::SKIP_DOTS)
8✔
281
            );
8✔
282
        } else {
283
            $cacheKey = self::CACHE_KEY_HELPER . \md5($pathOrCode);
38✔
284

285
            $phpCodes[$cacheKey]['content'] = $pathOrCode;
38✔
286
            $phpCodes[$cacheKey]['fileName'] = null;
38✔
287
        }
288

289
        $cache = new Cache(null, null, false);
156✔
290

291
        $phpFileArray = [];
156✔
292
        foreach ($phpFileIterators as $fileOrCode) {
156✔
293
            $path = $fileOrCode->getRealPath();
118✔
294
            if (!$path) {
118✔
295
                continue;
×
296
            }
297

298
            $fileExtensionFound = false;
118✔
299
            foreach ($fileExtensions as $fileExtension) {
118✔
300
                if (\substr($path, -\strlen($fileExtension)) === $fileExtension) {
118✔
301
                    $fileExtensionFound = true;
118✔
302

303
                    break;
118✔
304
                }
305
            }
306
            if ($fileExtensionFound === false) {
118✔
307
                continue;
×
308
            }
309

310
            foreach ($pathExcludeRegex as $regex) {
118✔
311
                if (\preg_match($regex, $path)) {
4✔
312
                    continue 2;
4✔
313
                }
314
            }
315

316
            $cacheKey = self::CACHE_KEY_HELPER . \md5($path) . '--' . \filemtime($path);
118✔
317
            if ($cache->getCacheIsReady() === true && $cache->existsItem($cacheKey)) {
118✔
318
                $response = $cache->getItem($cacheKey);
79✔
319
                /** @noinspection PhpSillyAssignmentInspection - helper for phpstan */
320
                /** @phpstan-var array{content: string, fileName: string, cacheKey: string} $response */
321
                $response = $response;
79✔
322

323
                $phpCodes[$response['cacheKey']]['content'] = $response['content'];
79✔
324
                $phpCodes[$response['cacheKey']]['fileName'] = $response['fileName'];
79✔
325

326
                continue;
79✔
327
            }
328

329
            $phpFileArray[$cacheKey] = $path;
47✔
330
        }
331

332
        $phpFileArrayChunks = \array_chunk($phpFileArray, Utils::getCpuCores(), true);
156✔
333
        foreach ($phpFileArrayChunks as $phpFileArrayChunk) {
156✔
334
            $filesystem = \React\Filesystem\Factory::create();
47✔
335

336
            foreach ($phpFileArrayChunk as $cacheKey => $path) {
47✔
337
                $phpFilePromises[] = $filesystem->detect($path)->then(
47✔
338
                    static function (NodeInterface $node) use ($path, $cacheKey): array {
47✔
339
                        if (!$node instanceof FileInterface) {
47✔
NEW
340
                            throw new \RuntimeException('Expected a file node for: ' . $path);
×
341
                        }
342

343
                        return [
47✔
344
                            'content'  => $node->getContents()->then(static function (string $contents): string {
47✔
345
                                return $contents;
47✔
346
                            }),
47✔
347
                            'fileName' => $path,
47✔
348
                            'cacheKey' => $cacheKey,
47✔
349
                        ];
47✔
350
                    },
47✔
351
                    function ($e) {
47✔
352
                        throw $e;
×
353
                    }
47✔
354
                );
47✔
355
            }
356

357
            /** @var list<array{content: \React\Promise\PromiseInterface<string>, fileName: string, cacheKey: string}> $phpFilePromiseResponses */
358
            $phpFilePromiseResponses = await(all($phpFilePromises));
47✔
359
            foreach ($phpFilePromiseResponses as $response) {
47✔
360
                $response['content'] = await($response['content']);
47✔
361

362
                assert(is_string($response['content']));
363
                assert(is_string($response['cacheKey']));
364
                assert($response['fileName'] === null || is_string($response['fileName']));
365

366
                @$cache->setItem($response['cacheKey'], $response);
47✔
367

368
                $phpCodes[$response['cacheKey']]['content'] = $response['content'];
47✔
369
                $phpCodes[$response['cacheKey']]['fileName'] = $response['fileName'];
47✔
370
            }
371
        }
372

373
        return $phpCodes;
156✔
374
    }
375

376
    /**
377
     * @param \voku\SimplePhpParser\Model\PHPClass   $class
378
     * @param \voku\SimplePhpParser\Model\PHPClass[] $classes
379
     * @param PHPInterface[]                         $interfaces
380
     * @param ParserContainer                        $parserContainer
381
     */
382
    private static function mergeInheritdocData(
383
        \voku\SimplePhpParser\Model\PHPClass $class,
384
        array $classes,
385
        array $interfaces,
386
        ParserContainer $parserContainer
387
    ): void {
388
        foreach ($class->properties as &$property) {
121✔
389
            if (!$class->parentClass) {
93✔
390
                break;
73✔
391
            }
392

393
            if (!$property->is_inheritdoc) {
40✔
394
                continue;
40✔
395
            }
396

397
            if (
398
                !isset($classes[$class->parentClass])
×
399
                &&
400
                \class_exists($class->parentClass, true)
×
401
            ) {
402
                $reflectionClassTmp = Utils::createClassReflectionInstance($class->parentClass);
×
403
                $classTmp = (new \voku\SimplePhpParser\Model\PHPClass($parserContainer))->readObjectFromReflection($reflectionClassTmp);
×
404
                if ($classTmp->name) {
×
405
                    $classes[$classTmp->name] = $classTmp;
×
406
                }
407
            }
408

409
            if (!isset($classes[$class->parentClass])) {
×
410
                continue;
×
411
            }
412

413
            if (!isset($classes[$class->parentClass]->properties[$property->name])) {
×
414
                continue;
×
415
            }
416

417
            $parentMethod = $classes[$class->parentClass]->properties[$property->name];
×
418

419
            foreach ($property as $key => &$value) {
×
420
                if (
UNCOV
421
                    $value === null
×
422
                    &&
UNCOV
423
                    $parentMethod->{$key} !== null
×
424
                    &&
UNCOV
425
                    \stripos($key, 'type') !== false
×
426
                ) {
UNCOV
427
                    $value = $parentMethod->{$key};
×
428
                }
429
            }
430
        }
431
        unset($property, $value); /* @phpstan-ignore-line ? */
121✔
432

433
        foreach ($class->methods as &$method) {
121✔
434
            if (!$method->is_inheritdoc) {
113✔
435
                continue;
109✔
436
            }
437

438
            foreach ($class->interfaces as $interfaceStr) {
31✔
439
                if (
440
                    !isset($interfaces[$interfaceStr])
31✔
441
                    &&
442
                    \interface_exists($interfaceStr, true)
31✔
443
                ) {
444
                    $reflectionInterfaceTmp = Utils::createClassReflectionInstance($interfaceStr);
23✔
445
                    $interfaceTmp = (new PHPInterface($parserContainer))->readObjectFromReflection($reflectionInterfaceTmp);
23✔
446
                    if ($interfaceTmp->name) {
23✔
447
                        $interfaces[$interfaceTmp->name] = $interfaceTmp;
23✔
448
                    }
449
                }
450

451
                if (!isset($interfaces[$interfaceStr])) {
31✔
UNCOV
452
                    continue;
×
453
                }
454

455
                if (!isset($interfaces[$interfaceStr]->methods[$method->name])) {
31✔
456
                    continue;
24✔
457
                }
458

459
                $interfaceMethod = $interfaces[$interfaceStr]->methods[$method->name];
19✔
460

461
                foreach ($method as $key => &$value) {
19✔
462
                    if (
463
                        $value === null
19✔
464
                        &&
465
                        $interfaceMethod->{$key} !== null
19✔
466
                        &&
467
                        \stripos($key, 'type') !== false
19✔
468
                    ) {
469
                        $value = $interfaceMethod->{$key};
19✔
470
                    }
471

472
                    if ($key === 'parameters') {
19✔
473
                        $parameterCounter = 0;
19✔
474
                        foreach ($value as &$parameter) {
19✔
475
                            ++$parameterCounter;
19✔
476

477
                            \assert($parameter instanceof \voku\SimplePhpParser\Model\PHPParameter);
478

479
                            $interfaceMethodParameter = null;
19✔
480
                            $parameterCounterInterface = 0;
19✔
481
                            foreach ($interfaceMethod->parameters as $parameterInterface) {
19✔
482
                                ++$parameterCounterInterface;
19✔
483

484
                                if ($parameterCounterInterface === $parameterCounter) {
19✔
485
                                    $interfaceMethodParameter = $parameterInterface;
19✔
486
                                }
487
                            }
488

489
                            if (!$interfaceMethodParameter) {
19✔
490
                                continue;
×
491
                            }
492

493
                            foreach ($parameter as $keyInner => &$valueInner) {
19✔
494
                                if (
495
                                    $valueInner === null
19✔
496
                                    &&
497
                                    $interfaceMethodParameter->{$keyInner} !== null
19✔
498
                                    &&
499
                                    \stripos($keyInner, 'type') !== false
19✔
500
                                ) {
501
                                    $valueInner = $interfaceMethodParameter->{$keyInner};
19✔
502
                                }
503
                            }
504
                            unset($valueInner); /* @phpstan-ignore-line ? */
19✔
505
                        }
506
                        unset($parameter);
19✔
507
                    }
508
                }
509
                unset($value); /* @phpstan-ignore-line ? */
19✔
510
            }
511

512
            if (!isset($classes[$class->parentClass])) {
31✔
513
                continue;
19✔
514
            }
515

516
            if (!isset($classes[$class->parentClass]->methods[$method->name])) {
20✔
UNCOV
517
                continue;
×
518
            }
519

520
            $parentMethod = $classes[$class->parentClass]->methods[$method->name];
20✔
521

522
            foreach ($method as $key => &$value) {
20✔
523
                if (
524
                    $value === null
20✔
525
                    &&
526
                    $parentMethod->{$key} !== null
20✔
527
                    &&
528
                    \stripos($key, 'type') !== false
20✔
529
                ) {
530
                    $value = $parentMethod->{$key};
20✔
531
                }
532

533
                if ($key === 'parameters') {
20✔
534
                    $parameterCounter = 0;
20✔
535
                    foreach ($value as &$parameter) {
20✔
536
                        ++$parameterCounter;
20✔
537

538
                        \assert($parameter instanceof \voku\SimplePhpParser\Model\PHPParameter);
539

540
                        $parentMethodParameter = null;
20✔
541
                        $parameterCounterParent = 0;
20✔
542
                        foreach ($parentMethod->parameters as $parameterParent) {
20✔
543
                            ++$parameterCounterParent;
20✔
544

545
                            if ($parameterCounterParent === $parameterCounter) {
20✔
546
                                $parentMethodParameter = $parameterParent;
20✔
547
                            }
548
                        }
549

550
                        if (!$parentMethodParameter) {
20✔
UNCOV
551
                            continue;
×
552
                        }
553

554
                        foreach ($parameter as $keyInner => &$valueInner) {
20✔
555
                            if (
556
                                $valueInner === null
20✔
557
                                &&
558
                                $parentMethodParameter->{$keyInner} !== null
20✔
559
                                &&
560
                                \stripos($keyInner, 'type') !== false
20✔
561
                            ) {
562
                                $valueInner = $parentMethodParameter->{$keyInner};
20✔
563
                            }
564
                        }
565
                    }
566
                }
567
            }
568
        }
569
    }
570
}
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