1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @author Patsura Dmitry https://github.com/ovr <[email protected]> |
4
|
|
|
*/ |
5
|
|
|
|
6
|
|
|
namespace PHPSA\Definition; |
7
|
|
|
|
8
|
|
|
use PHPSA\Compiler; |
9
|
|
|
use PHPSA\Context; |
10
|
|
|
use RuntimeException; |
11
|
|
|
|
12
|
|
|
class FileParser |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var \PhpParser\Parser |
16
|
|
|
*/ |
17
|
|
|
protected $parser; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var \PhpParser\NodeTraverser |
21
|
|
|
*/ |
22
|
|
|
protected $nodeTraverser; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var Compiler |
26
|
|
|
*/ |
27
|
|
|
protected $compiler; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @var \PHPSA\Compiler\DefinitionVisitor |
31
|
|
|
*/ |
32
|
|
|
protected $definitionVisitor; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param \PhpParser\Parser $parser |
36
|
|
|
* @param Compiler $compiler |
37
|
|
|
*/ |
38
|
1 |
|
public function __construct(\PhpParser\Parser $parser, Compiler $compiler) |
39
|
|
|
{ |
40
|
1 |
|
$this->nodeTraverser = new \PhpParser\NodeTraverser(); |
41
|
1 |
|
$this->nodeTraverser->addVisitor(new \PHPSA\Compiler\NameResolveVisitor); |
42
|
1 |
|
$this->nodeTraverser->addVisitor( |
43
|
1 |
|
$this->definitionVisitor = new \PHPSA\Compiler\DefinitionVisitor($compiler) |
44
|
|
|
); |
45
|
|
|
|
46
|
1 |
|
$this->parser = $parser; |
47
|
1 |
|
$this->compiler = $compiler; |
48
|
1 |
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param string $filepath |
52
|
|
|
* @param Context $context |
53
|
|
|
* @throws RuntimeException when filepath is not readable |
54
|
|
|
*/ |
55
|
1 |
|
public function parserFile($filepath, Context $context) |
56
|
|
|
{ |
57
|
1 |
|
$context->setFilepath($filepath); |
58
|
|
|
|
59
|
|
|
try { |
60
|
1 |
|
if (!is_readable($filepath)) { |
61
|
|
|
throw new RuntimeException('File ' . $filepath . ' is not readable'); |
62
|
|
|
} |
63
|
|
|
|
64
|
1 |
|
$context->debug('<comment>Precompile: ' . $filepath . '.</comment>'); |
65
|
|
|
|
66
|
1 |
|
$code = file_get_contents($filepath); |
67
|
1 |
|
$astTree = $this->parser->parse($code); |
68
|
|
|
|
69
|
1 |
|
$this->definitionVisitor->setFilePath($filepath); |
70
|
1 |
|
$this->nodeTraverser->traverse($astTree); |
|
|
|
|
71
|
|
|
|
72
|
|
|
$context->clear(); |
73
|
1 |
|
} catch (\PhpParser\Error $e) { |
74
|
|
|
$context->syntaxError($e, $filepath); |
75
|
1 |
|
} catch (\Exception $e) { |
76
|
1 |
|
$context->output->writeln("<error>{$e->getMessage()}</error>"); |
77
|
|
|
} |
78
|
1 |
|
} |
79
|
|
|
} |
80
|
|
|
|
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.