Skip to content

Commit 70f319a

Browse files
committed
StubParser
1 parent 67fbfae commit 70f319a

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

conf/config.stubValidator.neon

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ services:
1111
arguments:
1212
php8Parser: @php8PhpParser
1313

14+
defaultAnalysisParser:
15+
class: PHPStan\Parser\StubParser
16+
arguments!:
17+
parser: @php8PhpParser
18+
autowired: false
19+
1420
nodeScopeResolverReflector:
1521
factory: @stubReflector
1622

src/Parser/StubParser.php

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Parser;
4+
5+
use PhpParser\ErrorHandler\Collecting;
6+
use PhpParser\Node;
7+
use PhpParser\NodeTraverser;
8+
use PhpParser\NodeVisitor\NameResolver;
9+
use PHPStan\File\FileReader;
10+
use PHPStan\ShouldNotHappenException;
11+
12+
final class StubParser implements Parser
13+
{
14+
15+
public function __construct(
16+
private \PhpParser\Parser $parser,
17+
private NameResolver $nameResolver,
18+
)
19+
{
20+
}
21+
22+
/**
23+
* @param string $file path to a file to parse
24+
* @return Node\Stmt[]
25+
*/
26+
public function parseFile(string $file): array
27+
{
28+
try {
29+
return $this->parseString(FileReader::read($file));
30+
} catch (ParserErrorsException $e) {
31+
throw new ParserErrorsException($e->getErrors(), $file);
32+
}
33+
}
34+
35+
/**
36+
* @return Node\Stmt[]
37+
*/
38+
public function parseString(string $sourceCode): array
39+
{
40+
$errorHandler = new Collecting();
41+
$nodes = $this->parser->parse($sourceCode, $errorHandler);
42+
if ($errorHandler->hasErrors()) {
43+
throw new ParserErrorsException($errorHandler->getErrors(), null);
44+
}
45+
if ($nodes === null) {
46+
throw new ShouldNotHappenException();
47+
}
48+
49+
$nodeTraverser = new NodeTraverser();
50+
$nodeTraverser->addVisitor($this->nameResolver);
51+
52+
/** @var array<Node\Stmt> */
53+
return $nodeTraverser->traverse($nodes);
54+
}
55+
56+
}

0 commit comments

Comments
 (0)