Completed
Push — master ( edf0e8...eb9261 )
by Nikola
03:47
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 RunOpenCode\AbstractBuilder\Ast\Visitor\FileMetadataIntrospectionVisitor;
8
use RunOpenCode\AbstractBuilder\Exception\RuntimeException;
9
10
class MetadataLoader
11
{
12
    /**
13
     * @var \PhpParser\Parser
14
     */
15
    private $parser;
16
17
    /**
18
     * @var \PhpParser\NodeTraverser
19
     */
20
    private $traverser;
21
22
    /**
23
     * @var FileMetadataIntrospectionVisitor
24
     */
25
    private $introspector;
26
27
    private function __construct()
28
    {
29
        $this->parser = Parser::getInstance();
30
        $this->traverser = new NodeTraverser();
31
32
        $this->traverser->addVisitor(new NameResolver());
33
    }
34
35
    /**
36
     * Load file metadata
37
     *
38
     * @param string $arg
39
     *
40
     * @return Metadata\FileMetadata
41
     *
42
     * @throws \RunOpenCode\AbstractBuilder\Exception\RuntimeException
43
     */
44
    public function load($arg)
45
    {
46
        $filename = $arg;
47
48
        if (
49
            class_exists($arg, true)
50
            ||
51
            trait_exists($arg, true))
52
        {
53
            $filename = (new \ReflectionClass($arg))->getFileName();
54
        }
55
56
        if (null !== $this->introspector) {
57
            $this->traverser->removeVisitor($this->introspector);
58
        }
59
60
        $this->traverser->addVisitor($this->introspector = new FileMetadataIntrospectionVisitor($filename));
61
62
        if (!file_exists($filename)) {
63
            throw new RuntimeException(sprintf('Unable to load file metadata from "%s".', $arg));
64
        }
65
66
        $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...
67
68
        return $this->introspector->getMetadata();
69
    }
70
71
    /**
72
     * Singleton implementation
73
     *
74
     * @return MetadataLoader
75
     */
76
    public static function create()
77
    {
78
        return new static();
79
    }
80
}
81