Completed
Push — master ( 556a60...b1e8a1 )
by Nikola
02:34
created

MetadataLoader::load()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 0
cts 20
cp 0
rs 8.439
c 0
b 0
f 0
cc 5
eloc 14
nc 8
nop 1
crap 30
1
<?php
2
3
namespace RunOpenCode\AbstractBuilder\Ast;
4
5
use PhpParser\NodeTraverser;
6
use PhpParser\NodeVisitor\NameResolver;
7
use PhpParser\ParserFactory;
8
use RunOpenCode\AbstractBuilder\Ast\Visitor\FileMetadataIntrospectionVisitor;
9
use RunOpenCode\AbstractBuilder\Exception\RuntimeException;
10
11
class MetadataLoader
12
{
13
    /**
14
     * @var \PhpParser\Parser
15
     */
16
    private $parser;
17
18
    /**
19
     * @var \PhpParser\NodeTraverser
20
     */
21
    private $traverser;
22
23
    /**
24
     * @var FileMetadataIntrospectionVisitor
25
     */
26
    private $introspector;
27
28
    public function __construct()
29
    {
30
        $this->parser = (new ParserFactory())->create(ParserFactory::ONLY_PHP7);
31
        $this->traverser = new NodeTraverser();
32
33
        $this->traverser->addVisitor(new NameResolver());
34
    }
35
36
    /**
37
     * Load file metadata
38
     *
39
     * @param string $arg
40
     *
41
     * @return Metadata\FileMetadata
42
     *
43
     * @throws \RunOpenCode\AbstractBuilder\Exception\RuntimeException
44
     */
45
    public function load($arg)
46
    {
47
        $filename = $arg;
48
49
        if (
50
            class_exists($arg, true)
51
            ||
52
            trait_exists($arg, true))
53
        {
54
            $filename = (new \ReflectionClass($arg))->getFileName();
55
        }
56
57
        if (null !== $this->introspector) {
58
            $this->traverser->removeVisitor($this->introspector);
59
        }
60
61
        $this->traverser->addVisitor($this->introspector = new FileMetadataIntrospectionVisitor($filename));
62
63
        if (!file_exists($filename)) {
64
            throw new RuntimeException(sprintf('Unable to load file metadata from "%s".', $arg));
65
        }
66
67
        $this->traverser->traverse($this->parser->parse(file_get_contents($filename)));
0 ignored issues
show
Bug introduced by
It seems like $this->parser->parse(fil...et_contents($filename)) targeting PhpParser\Parser::parse() can also be of type null; however, PhpParser\NodeTraverser::traverse() does only seem to accept array<integer,object<PhpParser\Node>>, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
68
69
        return $this->introspector->getMetadata();
70
    }
71
}
72