Multiple   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 3
Bugs 0 Features 2
Metric Value
wmc 9
c 3
b 0
f 2
lcom 1
cbo 2
dl 0
loc 56
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getErrors() 0 3 1
B parse() 0 21 5
A tryParse() 0 9 2
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) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
60
        $errors = $parser->getErrors();
61
        return [$stmts, $errors, $error];
62
    }
63
}
64