-
Notifications
You must be signed in to change notification settings - Fork 34
/
refactor.php
363 lines (350 loc) · 11.8 KB
/
refactor.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
<?php
//Copyright (c) 2014, Carlos C
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//Copyright (c) 2014, Carlos C
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
//1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//
//2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//
//3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
define("ST_AT", "@");
define("ST_BRACKET_CLOSE", "]");
define("ST_BRACKET_OPEN", "[");
define("ST_COLON", ":");
define("ST_COMMA", ",");
define("ST_CONCAT", ".");
define("ST_CURLY_CLOSE", "}");
define("ST_CURLY_OPEN", "{");
define("ST_DIVIDE", "/");
define("ST_DOLLAR", "$");
define("ST_EQUAL", "=");
define("ST_EXCLAMATION", "!");
define("ST_IS_GREATER", ">");
define("ST_IS_SMALLER", "<");
define("ST_MINUS", "-");
define("ST_MODULUS", "%");
define("ST_PARENTHESES_CLOSE", ")");
define("ST_PARENTHESES_OPEN", "(");
define("ST_PLUS", "+");
define("ST_QUESTION", "?");
define("ST_QUOTE", '"');
define("ST_REFERENCE", "&");
define("ST_SEMI_COLON", ";");
define("ST_TIMES", "*");
if (!defined("T_POW")) {
define("T_POW", "**");
}
if (!defined("T_YIELD")) {
define("T_YIELD", "yield");
}
if (!defined("T_FINALLY")) {
define("T_FINALLY", "finally");
};
abstract class FormatterPass {
protected $indent_size = 1;
protected $indent_char = "\t";
protected $block_size = 1;
protected $new_line = "\n";
protected $indent = 0;
protected $for_idx = 0;
protected $code = '';
protected $ptr = 0;
protected $tkns = [];
abstract public function format($source);
protected function get_token($token) {
if (is_string($token)) {
return [$token, $token];
} else {
return $token;
}
}
protected function append_code($code = "", $trim = true) {
if ($trim) {
$this->code = rtrim($this->code) . $code;
} else {
$this->code .= $code;
}
}
protected function get_crlf_indent($in_for = false, $increment = 0) {
if ($in_for) {
++$this->for_idx;
if ($this->for_idx > 2) {
$this->for_idx = 0;
}
}
if ($this->for_idx === 0 || !$in_for) {
return $this->get_crlf() . $this->get_indent($increment);
} else {
return $this->get_space(false);
}
}
protected function get_crlf($true = true) {
return $true ? $this->new_line : "";
}
protected function get_space($true = true) {
return $true ? " " : "";
}
protected function get_indent($increment = 0) {
return str_repeat($this->indent_char, ($this->indent + $increment) * $this->indent_size);
}
protected function set_indent($increment) {
$this->indent += $increment;
if ($this->indent < 0) {
$this->indent = 0;
}
}
protected function inspect_token($delta = 1) {
if (!isset($this->tkns[$this->ptr + $delta])) {
return [null, null];
}
return $this->get_token($this->tkns[$this->ptr + $delta]);
}
protected function is_token($token, $prev = false) {
$i = $this->ptr;
if ($prev) {
while (--$i >= 0 && is_array($this->tkns[$i]) && $this->tkns[$i][0] === T_WHITESPACE);
} else {
while (++$i < sizeof($this->tkns) - 1 && is_array($this->tkns[$i]) && $this->tkns[$i][0] === T_WHITESPACE);
}
if (!isset($this->tkns[$i])) {
return false;
}
$found_token = $this->tkns[$i];
if (is_string($found_token) && $found_token === $token) {
return true;
} elseif (is_array($token) && is_array($found_token)) {
if (in_array($found_token[0], $token)) {
return true;
} elseif ($prev && $found_token[0] === T_OPEN_TAG) {
return true;
}
} elseif (is_array($token) && is_string($found_token) && in_array($found_token, $token)) {
return true;
}
return false;
}
protected function prev_token() {
$i = $this->ptr;
while (--$i >= 0 && is_array($this->tkns[$i]) && $this->tkns[$i][0] === T_WHITESPACE);
return $this->tkns[$i];
}
protected function has_ln_after() {
$id = null;
$text = null;
list($id, $text) = $this->inspect_token();
return T_WHITESPACE === $id && substr_count($text, $this->new_line) > 0;
}
protected function has_ln_before() {
$id = null;
$text = null;
list($id, $text) = $this->inspect_token(-1);
return T_WHITESPACE === $id && substr_count($text, $this->new_line) > 0;
}
protected function has_ln_prev_token() {
list($id, $text) = $this->get_token($this->prev_token());
return substr_count($text, $this->new_line) > 0;
}
protected function substr_count_trailing($haystack, $needle) {
$cnt = 0;
$i = strlen($haystack) - 1;
for ($i = $i; $i >= 0;--$i) {
$char = substr($haystack, $i, 1);
if ($needle === $char) {
++$cnt;
} elseif (' ' !== $char && "\t" !== $char) {
break;
}
}
return $cnt;
}
protected function printUntilTheEndOfString() {
while (list($index, $token) = each($this->tkns)) {
list($id, $text) = $this->get_token($token);
$this->ptr = $index;
$this->append_code($text, false);
if (ST_QUOTE == $id) {
break;
}
}
}
protected function walk_until($tknid) {
while (list($index, $token) = each($this->tkns)) {
list($id, $text) = $this->get_token($token);
$this->ptr = $index;
if ($id == $tknid) {
return [$id, $text];
}
}
}
};
final class RefactorPass extends FormatterPass {
private $from;
private $to;
public function __construct($from, $to) {
$this->setFrom($from);
$this->setTo($to);
}
private function setFrom($from) {
$tkns = token_get_all('<?php ' . $from);
array_shift($tkns);
$tkns = array_map(function ($v) {
return $this->get_token($v);
}, $tkns);
$this->from = $tkns;
return $this;
}
private function getFrom() {
return $this->from;
}
private function setTo($to) {
$tkns = token_get_all('<?php ' . $to);
array_shift($tkns);
$tkns = array_map(function ($v) {
return $this->get_token($v);
}, $tkns);
$this->to = $tkns;
return $this;
}
private function getTo() {
return $this->to;
}
public function format($source) {
$from = $this->getFrom();
$from_size = sizeof($from);
$from_str = implode('', array_map(function ($v) {
return $v[1];
}, $from));
$to = $this->getTo();
$to_str = implode('', array_map(function ($v) {
return $v[1];
}, $to));
$this->tkns = token_get_all($source);
$this->code = '';
while (list($index, $token) = each($this->tkns)) {
list($id, $text) = $this->get_token($token);
$this->ptr = $index;
if ($id == $from[0][0]) {
$match = true;
$buffer = $text;
$i = 1;
for ($i = 1; $i < $from_size; ++$i) {
list($index, $token) = each($this->tkns);
$this->ptr = $index;
list($id, $text) = $this->get_token($token);
$buffer .= $text;
if ($id != $from[$i][0]) {
$match = false;
break;
}
}
if ($match) {
$buffer = str_replace($from_str, $to_str, $buffer);
}
$this->append_code($buffer, false);
} else {
$this->append_code($text, false);
}
}
return $this->code;
}
};
final class CodeFormatter {
private $passes = [];
private $debug = false;
public function __construct($debug = false) {
$this->debug = (bool) $debug;
}
public function addPass(FormatterPass $pass) {
$this->passes[] = $pass;
}
public function formatCode($source = '') {
gc_enable();
$passes = array_map(
function ($pass) {
return clone $pass;
},
$this->passes
);
while (($pass = array_shift($passes))) {
$source = $pass->format($source);
gc_collect_cycles();
}
gc_disable();
return $source;
}
}
if (!isset($testEnv)) {
$opts = getopt('ho:', ['from:', 'to:', 'help']);
if (isset($opts['h']) || isset($opts['help'])) {
echo 'Usage: ' . $argv[0] . ' [-ho] [--from=from --to=to] <target>', PHP_EOL;
$options = [
'--from=from, --to=to' => 'Search for "from" and replace with "to" - context aware search and replace',
'-h, --help' => 'this help message',
'-o=file' => 'output the formatted code to "file"',
];
$maxLen = max(array_map(function ($v) {
return strlen($v);
}, array_keys($options)));
foreach ($options as $k => $v) {
echo ' ', str_pad($k, $maxLen), ' ', $v, PHP_EOL;
}
echo PHP_EOL, 'If <target> is blank, it reads from stdin', PHP_EOL;
die();
}
if (isset($opts['from']) && !isset($opts['to'])) {
fwrite(STDERR, "Refactor must have --from and --to parameters" . PHP_EOL);
exit(255);
}
$debug = false;
$fmt = new CodeFormatter($debug);
if (isset($opts['from']) && isset($opts['to'])) {
$argv = array_values(
array_filter($argv,
function ($v) {
$param_from = '--from';
$param_to = '--to';
return substr($v, 0, strlen($param_from)) !== $param_from && substr($v, 0, strlen($param_to)) !== $param_to;
}
)
);
$fmt->addPass(new RefactorPass($opts['from'], $opts['to']));
}
if (isset($opts['o'])) {
unset($argv[1]);
unset($argv[2]);
$argv = array_values($argv);
file_put_contents($opts['o'], $fmt->formatCode(file_get_contents($argv[1])));
} elseif (isset($argv[1]) && is_file($argv[1])) {
echo $fmt->formatCode(file_get_contents($argv[1]));
} elseif (isset($argv[1]) && is_dir($argv[1])) {
$dir = new RecursiveDirectoryIterator($argv[1]);
$it = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($it, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH);
foreach ($files as $file) {
$file = $file[0];
echo $file;
file_put_contents($file . '-tmp', $fmt->formatCode(file_get_contents($file)));
rename($file, $file . '~');
rename($file . '-tmp', $file);
echo PHP_EOL;
}
} else {
echo $fmt->formatCode(file_get_contents('php://stdin'));
}
}