Completed
Push — develop ( 1b34c6...481302 )
by Paul
02:47
created

PhpParser::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace PhpUnitGen\Parser;
4
5
use PhpParser\Error;
6
use PhpParser\Parser;
7
use PhpUnitGen\Exception\ParseException;
8
use PhpUnitGen\Model\ModelInterface\PhpFileModelInterface;
9
use PhpUnitGen\Model\PhpFileModel;
10
use PhpUnitGen\Parser\NodeParser\NodeParserInterface\PhpFileNodeParserInterface;
11
use PhpUnitGen\Parser\NodeParser\PhpFileNodeParser;
12
use PhpUnitGen\Parser\ParserInterface\PhpParserInterface;
13
14
/**
15
 * Class PhpParser.
16
 *
17
 * @author     Paul Thébaud <[email protected]>.
18
 * @copyright  2017-2018 Paul Thébaud <[email protected]>.
19
 * @license    https://opensource.org/licenses/MIT The MIT license.
20
 * @link       https://github.com/paul-thebaud/phpunit-generator
21
 * @since      Class available since Release 2.0.0.
22
 */
23
class PhpParser implements PhpParserInterface
24
{
25
    /**
26
     * @var Parser $phpParser A parser to parse php code as a string.
27
     */
28
    private $phpParser;
29
30
    /**
31
     * @var PhpFileNodeParserInterface $phpFileNodeParser A php file node parser to parse php nodes.
32
     */
33
    private $phpFileNodeParser;
34
35
    /**
36
     * PhpFileParser constructor.
37
     *
38
     * @param Parser                     $phpParser         The php code parser to use.
39
     * @param PhpFileNodeParserInterface $phpFileNodeParser The php file node parser to use.
40
     */
41
    public function __construct(
42
        Parser $phpParser,
43
        PhpFileNodeParserInterface $phpFileNodeParser
44
    ) {
45
        $this->phpParser         = $phpParser;
46
        $this->phpFileNodeParser = $phpFileNodeParser;
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function invoke(string $code): PhpFileModelInterface
53
    {
54
        try {
55
            $nodes = $this->phpParser->parse($code);
56
        } catch (Error $error) {
57
            throw new ParseException("Unable to parse given php code (maybe your code contains errors).");
58
        }
59
60
        $phpFileModel = new PhpFileModel();
61
        $phpFileModel = $this->phpFileNodeParser->preParseUses($nodes, $phpFileModel);
62
63
        /** @var PhpFileModelInterface $phpFileModel */
64
        $phpFileModel = $this->phpFileNodeParser->parseSubNodes($nodes, $phpFileModel);
65
66
        return $phpFileModel;
67
    }
68
}
69