Skip to content

Commit afc5092

Browse files
committed
Introducing SimpleParser
1 parent 93bbcf2 commit afc5092

File tree

2 files changed

+69
-2
lines changed

2 files changed

+69
-2
lines changed

conf/config.neon

+8-2
Original file line numberDiff line numberDiff line change
@@ -519,7 +519,7 @@ services:
519519
-
520520
class: PHPStan\Parser\CachedParser
521521
arguments:
522-
originalParser: @currentPhpVersionParser
522+
originalParser: @currentPhpVersionRichParser
523523
cachedNodesByStringCountMax: %cache.nodesByStringCountMax%
524524

525525
-
@@ -1173,13 +1173,19 @@ services:
11731173
directory: %tmpDir%/cache/PHPStan
11741174
autowired: no
11751175

1176-
currentPhpVersionParser:
1176+
currentPhpVersionRichParser:
11771177
class: PHPStan\Parser\RichParser
11781178
arguments:
11791179
parser: @currentPhpVersionPhpParser
11801180
lexer: @currentPhpVersionLexer
11811181
autowired: no
11821182

1183+
currentPhpVersionSimpleParser:
1184+
class: PHPStan\Parser\SimpleParser
1185+
arguments:
1186+
parser: @currentPhpVersionPhpParser
1187+
autowired: no
1188+
11831189
phpParserDecorator:
11841190
class: PHPStan\Parser\PhpParserDecorator
11851191
arguments:

src/Parser/SimpleParser.php

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

0 commit comments

Comments
 (0)