-
Notifications
You must be signed in to change notification settings - Fork 0
/
thrift2psr4.php
145 lines (123 loc) · 3.47 KB
/
thrift2psr4.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
<?php
/**
* Convert thrift generated files to psr4 standard
* @see https://gist.github.com/moolex/53168ac9d04fe52d5f0a47f14404391d
* User: moyo
* Date: 13/06/2017
* Time: 3:25 PM
*/
$argc < 3 && exit('Usage: ./thrift2psr4.php srcFolder dstFolder');
$src = $argv[1];
$dst = $argv[2];
is_dir($src) || exit('Source folder not exists');
is_dir($dst) || mkdir($dst, 0744);
scanning(realpath($src), realpath($dst));
function scanning($src, $dst)
{
$dirHandler = opendir($src);
while (false != $fileName = readdir($dirHandler))
{
if (in_array($fileName, ['.', '..'])) continue;
$filePath = "{$src}/{$fileName}";
if (is_dir($filePath))
{
scanning($filePath, "{$dst}/{$fileName}");
}
else
{
converting($filePath, $dst);
}
}
closedir($dirHandler);
}
function converting($file, $dst)
{
if (substr($file, - 4) != '.php') return;
$tokens = token_get_all(file_get_contents($file));
$namespace = '';
$use = $block = '';
$uses = $blocks = [];
$nsOpened = $useOpened = $inCoping = false;
$blockName = '';
$braceOpens = 0;
foreach ($tokens as $token)
{
if (is_array($token))
{
list($type, $value) = $token;
switch ($type)
{
case T_NAMESPACE:
$nsOpened = true;
break;
case T_USE:
$useOpened = true;
break;
case T_INTERFACE:
case T_CLASS:
$inCoping = true;
$block .= $value;
break;
case T_STRING:
case T_NS_SEPARATOR:
$nsOpened && $namespace .= $value;
$useOpened && $use .= $value;
if ($inCoping)
{
$block .= $value;
if ($type === T_STRING)
{
$blockName || $blockName = $value;
}
}
break;
default:
$inCoping && $block .= $value;
}
}
else
{
if ($token == ';')
{
$nsOpened && $nsOpened = false;
if ($useOpened)
{
$useOpened = false;
$uses[] = $use;
$use = '';
}
}
if ($inCoping)
{
$block .= $token;
$token == '{' && $braceOpens ++;
$token == '}' && $braceOpens --;
if ($braceOpens == 0)
{
$inCoping = false;
$blocks[$blockName] = $block;
$blockName = $block = '';
}
}
}
}
foreach ($blocks as $name => $block)
{
$cLines = [];
$cLines[] = '<?php';
$cLines[] = "namespace {$namespace};";
$cLines[] = '';
array_walk($uses, function ($class) use (&$cLines) {
$cLines[] = "use {$class};";
});
$cLines[] = '';
$cLines[] = $block;
writing("{$dst}/{$name}.php", implode("\n", $cLines));
}
}
function writing($file, $content)
{
$dir = dirname($file);
is_dir($dir) || mkdir($dir, 0744, true);
file_put_contents($file, $content);
}