-
Notifications
You must be signed in to change notification settings - Fork 478
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
93bbcf2
commit afc5092
Showing
2 changed files
with
69 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
<?php declare(strict_types = 1); | ||
|
||
namespace PHPStan\Parser; | ||
|
||
use PhpParser\ErrorHandler\Collecting; | ||
use PhpParser\NodeTraverser; | ||
use PhpParser\NodeVisitor\NameResolver; | ||
use PHPStan\File\FileReader; | ||
|
||
class SimpleParser implements Parser | ||
{ | ||
|
||
private \PhpParser\Parser $parser; | ||
|
||
private NameResolver $nameResolver; | ||
|
||
public function __construct( | ||
\PhpParser\Parser $parser, | ||
NameResolver $nameResolver | ||
) | ||
{ | ||
$this->parser = $parser; | ||
$this->nameResolver = $nameResolver; | ||
} | ||
|
||
/** | ||
* @param string $file path to a file to parse | ||
* @return \PhpParser\Node\Stmt[] | ||
*/ | ||
public function parseFile(string $file): array | ||
{ | ||
try { | ||
return $this->parseString(FileReader::read($file)); | ||
} catch (\PHPStan\Parser\ParserErrorsException $e) { | ||
throw new \PHPStan\Parser\ParserErrorsException($e->getErrors(), $file); | ||
} | ||
} | ||
|
||
/** | ||
* @param string $sourceCode | ||
* @return \PhpParser\Node\Stmt[] | ||
*/ | ||
public function parseString(string $sourceCode): array | ||
{ | ||
$errorHandler = new Collecting(); | ||
$nodes = $this->parser->parse($sourceCode, $errorHandler); | ||
if ($errorHandler->hasErrors()) { | ||
throw new \PHPStan\Parser\ParserErrorsException($errorHandler->getErrors(), null); | ||
} | ||
if ($nodes === null) { | ||
throw new \PHPStan\ShouldNotHappenException(); | ||
} | ||
|
||
$nodeTraverser = new NodeTraverser(); | ||
$nodeTraverser->addVisitor($this->nameResolver); | ||
|
||
/** @var array<\PhpParser\Node\Stmt> */ | ||
return $nodeTraverser->traverse($nodes); | ||
} | ||
|
||
} |