PhpParser::getNodes()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.1481

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 4
cts 6
cp 0.6667
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 1
crap 2.1481
1
<?php
2
3
namespace Kambo\Testing\ClassOpener\ClassManipulation\Reader;
4
5
use Kambo\Testing\ClassOpener\ClassManipulation\Reader;
6
use Kambo\Testing\ClassOpener\ClassManipulation\Locator;
7
use Kambo\Testing\ClassOpener\ClassManipulation\Exception\ParseErrorException;
8
9
use PhpParser\Error;
10
use PhpParser\ParserFactory;
11
12
/**
13
 * Source code class reader, which will parse code into nodes with PHP parser.
14
 *
15
 * @author  Bohuslav Simek <[email protected]>
16
 * @license MIT
17
 */
18
class PhpParser implements Reader
19
{
20
    private $reflectionClassLocator;
21
    private $astParser;
22
23
    /**
24
     * Constructor
25
     *
26
     * @param Locator $locator Class source code locator
27
     */
28 4
    public function __construct(Locator $locator)
29
    {
30 4
        $this->reflectionClassLocator = $locator;
31 4
        $this->astParser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
32 4
    }
33
34
    /**
35
     * Parses PHP code into a node tree.
36
     *
37
     * @param string $className A fully qualified name of class, which will be parsed
38
     *
39
     * @return Node[] Array of php nodes
40
     */
41 4
    public function getNodes(string $className) : array
42
    {
43 4
        $fileName = $this->reflectionClassLocator->locate($className);
44
        try {
45 3
            $ast = $this->astParser->parse(file_get_contents($fileName));
46
        } catch (Error $error) {
47
            throw new ParseErrorException("File Parser error: {$error->getMessage()}");
48
        }
49
50 3
        return $ast;
51
    }
52
}
53