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
|
|
|
} |