php-parser/lib/PhpParser/Parser/Multiple.php

56 lines
1.6 KiB
PHP
Raw Normal View History

2017-08-18 22:57:27 +02:00
<?php declare(strict_types=1);
2015-06-13 13:30:20 +02:00
namespace PhpParser\Parser;
use PhpParser\Error;
use PhpParser\ErrorHandler;
use PhpParser\Parser;
2015-06-13 13:30:20 +02:00
2018-01-10 17:24:26 +01:00
class Multiple implements Parser
{
/** @var Parser[] List of parsers to try, in order of preference */
2015-06-13 13:30:20 +02:00
private $parsers;
/**
* Create a parser which will try multiple parsers in an order of preference.
*
2015-07-12 22:00:02 +02:00
* Parsers will be invoked in the order they're provided to the constructor. If one of the
* parsers runs without throwing, it's output is returned. Otherwise the exception that the
* first parser generated is thrown.
2015-06-13 13:30:20 +02:00
*
* @param Parser[] $parsers
2015-06-13 13:30:20 +02:00
*/
public function __construct(array $parsers) {
$this->parsers = $parsers;
}
2017-04-28 21:40:59 +02:00
public function parse(string $code, ErrorHandler $errorHandler = null) {
if (null === $errorHandler) {
$errorHandler = new ErrorHandler\Throwing;
}
list($firstStmts, $firstError) = $this->tryParse($this->parsers[0], $errorHandler, $code);
if ($firstError === null) {
2015-06-13 13:30:20 +02:00
return $firstStmts;
}
for ($i = 1, $c = count($this->parsers); $i < $c; ++$i) {
list($stmts, $error) = $this->tryParse($this->parsers[$i], $errorHandler, $code);
if ($error === null) {
2015-06-13 13:30:20 +02:00
return $stmts;
}
}
throw $firstError;
2015-06-13 13:30:20 +02:00
}
private function tryParse(Parser $parser, ErrorHandler $errorHandler, $code) {
2015-06-13 13:30:20 +02:00
$stmts = null;
$error = null;
try {
$stmts = $parser->parse($code, $errorHandler);
2015-06-13 13:30:20 +02:00
} catch (Error $error) {}
return [$stmts, $error];
2015-06-13 13:30:20 +02:00
}
}