Repository navigation
Expand file tree
/
Copy pathRectorParser.php
More file actions
72 lines (59 loc) · 1.94 KB
/
Copy pathRectorParser.php
File metadata and controls
72 lines (59 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
declare(strict_types=1);
namespace Rector\PhpParser\Parser;
use PhpParser\Node\Stmt;
use PhpParser\ParserFactory;
use PhpParser\PhpVersion;
use PHPStan\Parser\Parser;
use PHPStan\Parser\RichParser;
use Rector\PhpParser\ValueObject\StmtsAndTokens;
use Rector\Util\Reflection\PrivatesAccessor;
final readonly class RectorParser
{
/**
* @param RichParser $parser
*/
public function __construct(
private Parser $parser,
private PrivatesAccessor $privatesAccessor
) {
}
/**
* @api used by rector-symfony
*
* @return Stmt[]
*/
public function parseFile(string $filePath): array
{
return $this->parser->parseFile($filePath);
}
/**
* @return Stmt[]
*/
public function parseString(string $fileContent): array
{
return $this->parser->parseString($fileContent);
}
public function parseFileContentToStmtsAndTokens(
string $fileContent,
bool $forNewestSupportedVersion = true
): StmtsAndTokens {
if (! $forNewestSupportedVersion) {
// don't directly change PHPStan Parser service
// to avoid reuse on next file
$phpstanParser = clone $this->parser;
$parserFactory = new ParserFactory();
$parser = $parserFactory->createForVersion(PhpVersion::fromString('7.0'));
$this->privatesAccessor->setPrivateProperty($phpstanParser, 'parser', $parser);
return $this->resolveStmtsAndTokens($phpstanParser, $fileContent);
}
return $this->resolveStmtsAndTokens($this->parser, $fileContent);
}
private function resolveStmtsAndTokens(Parser $parser, string $fileContent): StmtsAndTokens
{
$stmts = $parser->parseString($fileContent);
$innerParser = $this->privatesAccessor->getPrivateProperty($parser, 'parser');
$tokens = $innerParser->getTokens();
return new StmtsAndTokens($stmts, $tokens);
}
}