Reader   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
dl 0
loc 38
rs 10
c 1
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A read() 0 15 4
A __construct() 0 8 1
1
<?php
2
3
namespace BiiiiiigMonster\LaravelEnum;
4
5
use InvalidArgumentException;
6
use PhpParser\NodeTraverser;
7
use PhpParser\NodeVisitor;
8
use PhpParser\Parser;
9
use PhpParser\ParserFactory;
10
use RuntimeException;
11
use SplFileInfo;
12
13
class Reader
14
{
15
    private SplFileInfo $file;
16
17
    private Parser $parser;
18
19
    private NodeTraverser $traverser;
20
21
    private array $visitors;
22
23
    /**
24
     * Reader constructor.
25
     */
26
    public function __construct(SplFileInfo $file, NodeVisitor ...$visitors)
27
    {
28
        $this->parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
29
        $this->traverser = new NodeTraverser();
30
31
        $this->file = $file;
32
        $this->visitors = $visitors;
33
        $this->read();
34
    }
35
36
    private function read(): void
37
    {
38
        if (empty($contents = file_get_contents($this->file->getPathname()))) {
39
            throw new InvalidArgumentException('file contents get fail.');
40
        }
41
42
        if (is_null($ast = $this->parser->parse($contents))) {
43
            throw new RuntimeException('file contents parse error.');
44
        }
45
46
        // add visitor.
47
        foreach ($this->visitors as $visitor) {
48
            $this->traverser->addVisitor($visitor);
49
        }
50
        $this->traverser->traverse($ast);
51
    }
52
}
53