|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace PhpParser\Parser; |
|
4
|
|
|
|
|
5
|
|
|
use PhpParser\Error; |
|
6
|
|
|
use PhpParser\Parser; |
|
7
|
|
|
|
|
8
|
|
|
class Multiple implements Parser { |
|
9
|
|
|
/** @var Parser[] List of parsers to try, in order of preference */ |
|
10
|
|
|
private $parsers; |
|
11
|
|
|
/** @var Error[] Errors collected during last parse */ |
|
12
|
|
|
private $errors; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* Create a parser which will try multiple parsers in an order of preference. |
|
16
|
|
|
* |
|
17
|
|
|
* Parsers will be invoked in the order they're provided to the constructor. If one of the |
|
18
|
|
|
* parsers runs without errors, it's output is returned. Otherwise the errors (and |
|
19
|
|
|
* PhpParser\Error exception) of the first parser are used. |
|
20
|
|
|
* |
|
21
|
|
|
* @param Parser[] $parsers |
|
22
|
|
|
*/ |
|
23
|
|
|
public function __construct(array $parsers) { |
|
24
|
|
|
$this->parsers = $parsers; |
|
25
|
|
|
$this->errors = []; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public function parse($code) { |
|
29
|
|
|
list($firstStmts, $firstErrors, $firstError) = $this->tryParse($this->parsers[0], $code); |
|
30
|
|
|
if ($firstErrors === []) { |
|
31
|
|
|
$this->errors = []; |
|
32
|
|
|
return $firstStmts; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
for ($i = 1, $c = count($this->parsers); $i < $c; ++$i) { |
|
36
|
|
|
list($stmts, $errors) = $this->tryParse($this->parsers[$i], $code); |
|
37
|
|
|
if ($errors === []) { |
|
38
|
|
|
$this->errors = []; |
|
39
|
|
|
return $stmts; |
|
40
|
|
|
} |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
$this->errors = $firstErrors; |
|
44
|
|
|
if ($firstError) { |
|
45
|
|
|
throw $firstError; |
|
46
|
|
|
} |
|
47
|
|
|
return $firstStmts; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
public function getErrors() { |
|
51
|
|
|
return $this->errors; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
private function tryParse(Parser $parser, $code) { |
|
55
|
|
|
$stmts = null; |
|
56
|
|
|
$error = null; |
|
57
|
|
|
try { |
|
58
|
|
|
$stmts = $parser->parse($code); |
|
59
|
|
|
} catch (Error $error) {} |
|
|
|
|
|
|
60
|
|
|
$errors = $parser->getErrors(); |
|
61
|
|
|
return [$stmts, $errors, $error]; |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|