LuaToPhpConverter::parseTable()   B
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5.0592

Importance

Changes 0
Metric Value
dl 0
loc 19
c 0
b 0
f 0
ccs 13
cts 15
cp 0.8667
rs 8.8571
nc 5
cc 5
eloc 14
nop 1
crap 5.0592
1
<?php
2
3
namespace Vlaswinkel\Lua;
4
5
use Vlaswinkel\Lua\AST\ASTNode;
6
use Vlaswinkel\Lua\AST\LiteralASTNode;
7
use Vlaswinkel\Lua\AST\NilASTNode;
8
use Vlaswinkel\Lua\AST\TableASTNode;
9
use Vlaswinkel\Lua\AST\TableEntryASTNode;
10
11
/**
12
 * Class LuaToPhpConverter
13
 *
14
 * @author  Koen Vlaswinkel <[email protected]>
15
 * @package Vlaswinkel\Lua
16
 */
17
class LuaToPhpConverter {
18
    /**
19
     * @param ASTNode $input
20
     *
21
     * @return array
22
     * @throws ParseException
23
     */
24 8
    public static function convertToPhpValue($input) {
25 8
        return self::parseValue($input);
26
    }
27
28
    /**
29
     * @param ASTNode $input
30
     *
31
     * @return mixed
32
     * @throws ParseException
33
     */
34 8
    private static function parseValue($input) {
35 8
        if ($input instanceof TableASTNode) {
36 5
            return self::parseTable($input);
37
        }
38 7
        if (!($input instanceof ASTNode)) {
39
            throw new ParseException("Unexpected AST node: " . get_class($input));
40
        }
41 7
        if ($input instanceof LiteralASTNode) {
42 6
            return $input->getValue();
43
        }
44 2
        if ($input instanceof NilASTNode) {
45 2
            return null;
46
        }
47
        throw new ParseException("Unexpected AST node: " . $input->getName());
48
    }
49
50
    /**
51
     * @param $input
52
     *
53
     * @return array
54
     * @throws ParseException
55
     */
56 5
    private static function parseTable($input) {
57 5
        $data = [];
58 5
        if (!($input instanceof TableASTNode)) {
59
            throw new ParseException("Unexpected AST node: " . get_class($input));
60
        }
61 5
        foreach ($input->getEntries() as $token) {
62 4
            if (!($token instanceof TableEntryASTNode)) {
63
                throw new ParseException("Unexpected token: " . $token->getName());
64
            }
65 4
            $value = self::parseValue($token->getValue());
66 4
            if ($token->hasKey()) {
67 4
                $key        = self::parseValue($token->getKey());
68 4
                $data[$key] = $value;
69 4
            } else {
70 2
                $data[] = $value;
71
            }
72 5
        }
73 5
        return $data;
74
    }
75
}