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