PhpCodeParser::parse()   A
last analyzed

Complexity

Conditions 2
Paths 6

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 6
cts 8
cp 0.75
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 6
nop 1
crap 2.0625
1
<?php declare(strict_types=1);
2
3
namespace Bigwhoop\Trumpet\CodeParsing\Php;
4
5
use Bigwhoop\Trumpet\CodeParsing\ParserException;
6
use PhpParser\Error;
7
use PhpParser\ParserAbstract as Parser;
8
use PhpParser\NodeTraverserInterface as NodeTraverser;
9
use PhpParser\PrettyPrinterAbstract as Printer;
10
11
final class PhpCodeParser
12
{
13
    /** @var Parser */
14
    private $parser;
15
16
    /** @var NodeTraverser */
17
    private $nodeTraverser;
18
19
    /** @var Printer */
20
    private $printer;
21
22 1
    public function __construct(Parser $parser, NodeTraverser $nodeTraverser, Printer $printer)
23
    {
24 1
        $this->parser = $parser;
25 1
        $this->nodeTraverser = $nodeTraverser;
26 1
        $this->printer = $printer;
27 1
    }
28
29 11
    public function parse(string $code): ParserResult
30
    {
31
        try {
32 11
            $stmts = $this->parser->parse($code);
33
34 11
            $visitor = $this->createVisitor();
35 11
            $this->nodeTraverser->addVisitor($visitor);
36
37 11
            $this->nodeTraverser->traverse($stmts);
0 ignored issues
show
Bug introduced by
It seems like $stmts defined by $this->parser->parse($code) on line 32 can also be of type null; however, PhpParser\NodeTraverserInterface::traverse() does only seem to accept array<integer,object<PhpParser\Node>>, maybe add an additional type check?

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:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
38
39 11
            return $visitor->getResult();
40
        } catch (Error $e) {
41
            throw new ParserException("Failed to parse PHP file: ".$e->getMessage(), $e->getCode(), $e);
42
        }
43
    }
44
    
45 11
    private function createVisitor(): NodeVisitor
46
    {
47 11
        return new NodeVisitor($this->printer);
48
    }
49
}
50