PhpToNodeFilesConverter::convert()   A
last analyzed

Complexity

Conditions 3
Paths 9

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 16
c 1
b 0
f 1
nc 9
nop 0
dl 0
loc 24
rs 9.7333
1
<?php
2
declare(strict_types=1);
3
4
namespace hipanel\rbac\console\converter;
5
6
use hipanel\rbac\console\converter\formatter\EnumRowItemBuilder;
7
use PhpParser\NodeTraverser;
8
use PhpParser\Parser;
9
use PhpParser\ParserFactory;
10
use Throwable;
11
use yii\helpers\FileHelper;
12
13
final class PhpToNodeFilesConverter implements ConverterInterface
14
{
15
    private const EXPORT_FILE_NAME = 'index.ts';
16
17
    public string $storageDir;
18
19
    public string $convertFile;
20
21
    private Parser $parser;
22
23
    public function __construct()
24
    {
25
        $this->parser = (new ParserFactory())
26
            ->create(ParserFactory::PREFER_PHP7);
27
    }
28
29
    public function convert(): void
30
    {
31
        $traverser = new NodeTraverser();
32
        $visitor = new Visitor();
33
        $traverser->addVisitor($visitor);
34
35
        try {
36
            $stmts = $this->parser->parse(file_get_contents($this->convertFile));
37
            $traverser->traverse($stmts);
0 ignored issues
show
Bug introduced by
It seems like $stmts can also be of type null; however, parameter $nodes of PhpParser\NodeTraverser::traverse() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

37
            $traverser->traverse(/** @scrutinizer ignore-type */ $stmts);
Loading history...
38
39
            $output = TsFileGenerator::fromParts(
40
                (new TsObjectGenerator('RoleHierarchy', require $this->convertFile))->generate(),
41
                (new TsEnumGenerator('Role', $visitor->getRoles()))->withRowFormatter(new EnumRowItemBuilder())->generate(),
42
                (new TsEnumGenerator('Permission', $visitor->getPermissions()))->generate(),
43
            );
44
45
            if (!is_dir($this->storageDir)) {
46
                FileHelper::createDirectory($this->storageDir);
47
            }
48
49
            $targetFile = $this->storageDir . '/' . self::EXPORT_FILE_NAME;
50
            file_put_contents($targetFile, $output, LOCK_EX);
51
        } catch (Throwable $e) {
52
            echo 'Falied to parse file: ' . $e->getMessage();
53
        }
54
    }
55
}
56