PageRenderTime 26ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Packages/phpfmt/refactor.php

https://gitlab.com/frenlee710/sublime
PHP | 363 lines | 326 code | 13 blank | 24 comment | 65 complexity | 98add8e3c627ae8c4c4ea046d69b5724 MD5 | raw file
  1. <?php
  2. //Copyright (c) 2014, Carlos C
  3. //All rights reserved.
  4. //
  5. //Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  6. //
  7. //1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  8. //
  9. //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.
  10. //
  11. //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.
  12. //
  13. //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.
  14. //Copyright (c) 2014, Carlos C
  15. //All rights reserved.
  16. //
  17. //Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  18. //
  19. //1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  20. //
  21. //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.
  22. //
  23. //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.
  24. //
  25. //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.
  26. define("ST_AT", "@");
  27. define("ST_BRACKET_CLOSE", "]");
  28. define("ST_BRACKET_OPEN", "[");
  29. define("ST_COLON", ":");
  30. define("ST_COMMA", ",");
  31. define("ST_CONCAT", ".");
  32. define("ST_CURLY_CLOSE", "}");
  33. define("ST_CURLY_OPEN", "{");
  34. define("ST_DIVIDE", "/");
  35. define("ST_DOLLAR", "$");
  36. define("ST_EQUAL", "=");
  37. define("ST_EXCLAMATION", "!");
  38. define("ST_IS_GREATER", ">");
  39. define("ST_IS_SMALLER", "<");
  40. define("ST_MINUS", "-");
  41. define("ST_MODULUS", "%");
  42. define("ST_PARENTHESES_CLOSE", ")");
  43. define("ST_PARENTHESES_OPEN", "(");
  44. define("ST_PLUS", "+");
  45. define("ST_QUESTION", "?");
  46. define("ST_QUOTE", '"');
  47. define("ST_REFERENCE", "&");
  48. define("ST_SEMI_COLON", ";");
  49. define("ST_TIMES", "*");
  50. if (!defined("T_POW")) {
  51. define("T_POW", "**");
  52. }
  53. if (!defined("T_YIELD")) {
  54. define("T_YIELD", "yield");
  55. }
  56. if (!defined("T_FINALLY")) {
  57. define("T_FINALLY", "finally");
  58. };
  59. abstract class FormatterPass {
  60. protected $indent_size = 1;
  61. protected $indent_char = "\t";
  62. protected $block_size = 1;
  63. protected $new_line = "\n";
  64. protected $indent = 0;
  65. protected $for_idx = 0;
  66. protected $code = '';
  67. protected $ptr = 0;
  68. protected $tkns = [];
  69. abstract public function format($source);
  70. protected function get_token($token) {
  71. if (is_string($token)) {
  72. return [$token, $token];
  73. } else {
  74. return $token;
  75. }
  76. }
  77. protected function append_code($code = "", $trim = true) {
  78. if ($trim) {
  79. $this->code = rtrim($this->code) . $code;
  80. } else {
  81. $this->code .= $code;
  82. }
  83. }
  84. protected function get_crlf_indent($in_for = false, $increment = 0) {
  85. if ($in_for) {
  86. ++$this->for_idx;
  87. if ($this->for_idx > 2) {
  88. $this->for_idx = 0;
  89. }
  90. }
  91. if ($this->for_idx === 0 || !$in_for) {
  92. return $this->get_crlf() . $this->get_indent($increment);
  93. } else {
  94. return $this->get_space(false);
  95. }
  96. }
  97. protected function get_crlf($true = true) {
  98. return $true ? $this->new_line : "";
  99. }
  100. protected function get_space($true = true) {
  101. return $true ? " " : "";
  102. }
  103. protected function get_indent($increment = 0) {
  104. return str_repeat($this->indent_char, ($this->indent + $increment) * $this->indent_size);
  105. }
  106. protected function set_indent($increment) {
  107. $this->indent += $increment;
  108. if ($this->indent < 0) {
  109. $this->indent = 0;
  110. }
  111. }
  112. protected function inspect_token($delta = 1) {
  113. if (!isset($this->tkns[$this->ptr + $delta])) {
  114. return [null, null];
  115. }
  116. return $this->get_token($this->tkns[$this->ptr + $delta]);
  117. }
  118. protected function is_token($token, $prev = false) {
  119. $i = $this->ptr;
  120. if ($prev) {
  121. while (--$i >= 0 && is_array($this->tkns[$i]) && $this->tkns[$i][0] === T_WHITESPACE);
  122. } else {
  123. while (++$i < sizeof($this->tkns) - 1 && is_array($this->tkns[$i]) && $this->tkns[$i][0] === T_WHITESPACE);
  124. }
  125. if (!isset($this->tkns[$i])) {
  126. return false;
  127. }
  128. $found_token = $this->tkns[$i];
  129. if (is_string($found_token) && $found_token === $token) {
  130. return true;
  131. } elseif (is_array($token) && is_array($found_token)) {
  132. if (in_array($found_token[0], $token)) {
  133. return true;
  134. } elseif ($prev && $found_token[0] === T_OPEN_TAG) {
  135. return true;
  136. }
  137. } elseif (is_array($token) && is_string($found_token) && in_array($found_token, $token)) {
  138. return true;
  139. }
  140. return false;
  141. }
  142. protected function prev_token() {
  143. $i = $this->ptr;
  144. while (--$i >= 0 && is_array($this->tkns[$i]) && $this->tkns[$i][0] === T_WHITESPACE);
  145. return $this->tkns[$i];
  146. }
  147. protected function has_ln_after() {
  148. $id = null;
  149. $text = null;
  150. list($id, $text) = $this->inspect_token();
  151. return T_WHITESPACE === $id && substr_count($text, $this->new_line) > 0;
  152. }
  153. protected function has_ln_before() {
  154. $id = null;
  155. $text = null;
  156. list($id, $text) = $this->inspect_token(-1);
  157. return T_WHITESPACE === $id && substr_count($text, $this->new_line) > 0;
  158. }
  159. protected function has_ln_prev_token() {
  160. list($id, $text) = $this->get_token($this->prev_token());
  161. return substr_count($text, $this->new_line) > 0;
  162. }
  163. protected function substr_count_trailing($haystack, $needle) {
  164. $cnt = 0;
  165. $i = strlen($haystack) - 1;
  166. for ($i = $i; $i >= 0;--$i) {
  167. $char = substr($haystack, $i, 1);
  168. if ($needle === $char) {
  169. ++$cnt;
  170. } elseif (' ' !== $char && "\t" !== $char) {
  171. break;
  172. }
  173. }
  174. return $cnt;
  175. }
  176. protected function printUntilTheEndOfString() {
  177. while (list($index, $token) = each($this->tkns)) {
  178. list($id, $text) = $this->get_token($token);
  179. $this->ptr = $index;
  180. $this->append_code($text, false);
  181. if (ST_QUOTE == $id) {
  182. break;
  183. }
  184. }
  185. }
  186. protected function walk_until($tknid) {
  187. while (list($index, $token) = each($this->tkns)) {
  188. list($id, $text) = $this->get_token($token);
  189. $this->ptr = $index;
  190. if ($id == $tknid) {
  191. return [$id, $text];
  192. }
  193. }
  194. }
  195. };
  196. final class RefactorPass extends FormatterPass {
  197. private $from;
  198. private $to;
  199. public function __construct($from, $to) {
  200. $this->setFrom($from);
  201. $this->setTo($to);
  202. }
  203. private function setFrom($from) {
  204. $tkns = token_get_all('<?php ' . $from);
  205. array_shift($tkns);
  206. $tkns = array_map(function ($v) {
  207. return $this->get_token($v);
  208. }, $tkns);
  209. $this->from = $tkns;
  210. return $this;
  211. }
  212. private function getFrom() {
  213. return $this->from;
  214. }
  215. private function setTo($to) {
  216. $tkns = token_get_all('<?php ' . $to);
  217. array_shift($tkns);
  218. $tkns = array_map(function ($v) {
  219. return $this->get_token($v);
  220. }, $tkns);
  221. $this->to = $tkns;
  222. return $this;
  223. }
  224. private function getTo() {
  225. return $this->to;
  226. }
  227. public function format($source) {
  228. $from = $this->getFrom();
  229. $from_size = sizeof($from);
  230. $from_str = implode('', array_map(function ($v) {
  231. return $v[1];
  232. }, $from));
  233. $to = $this->getTo();
  234. $to_str = implode('', array_map(function ($v) {
  235. return $v[1];
  236. }, $to));
  237. $this->tkns = token_get_all($source);
  238. $this->code = '';
  239. while (list($index, $token) = each($this->tkns)) {
  240. list($id, $text) = $this->get_token($token);
  241. $this->ptr = $index;
  242. if ($id == $from[0][0]) {
  243. $match = true;
  244. $buffer = $text;
  245. $i = 1;
  246. for ($i = 1; $i < $from_size; ++$i) {
  247. list($index, $token) = each($this->tkns);
  248. $this->ptr = $index;
  249. list($id, $text) = $this->get_token($token);
  250. $buffer .= $text;
  251. if ($id != $from[$i][0]) {
  252. $match = false;
  253. break;
  254. }
  255. }
  256. if ($match) {
  257. $buffer = str_replace($from_str, $to_str, $buffer);
  258. }
  259. $this->append_code($buffer, false);
  260. } else {
  261. $this->append_code($text, false);
  262. }
  263. }
  264. return $this->code;
  265. }
  266. };
  267. final class CodeFormatter {
  268. private $passes = [];
  269. private $debug = false;
  270. public function __construct($debug = false) {
  271. $this->debug = (bool) $debug;
  272. }
  273. public function addPass(FormatterPass $pass) {
  274. $this->passes[] = $pass;
  275. }
  276. public function formatCode($source = '') {
  277. gc_enable();
  278. $passes = array_map(
  279. function ($pass) {
  280. return clone $pass;
  281. },
  282. $this->passes
  283. );
  284. while (($pass = array_shift($passes))) {
  285. $source = $pass->format($source);
  286. gc_collect_cycles();
  287. }
  288. gc_disable();
  289. return $source;
  290. }
  291. }
  292. if (!isset($testEnv)) {
  293. $opts = getopt('ho:', ['from:', 'to:', 'help']);
  294. if (isset($opts['h']) || isset($opts['help'])) {
  295. echo 'Usage: ' . $argv[0] . ' [-ho] [--from=from --to=to] <target>', PHP_EOL;
  296. $options = [
  297. '--from=from, --to=to' => 'Search for "from" and replace with "to" - context aware search and replace',
  298. '-h, --help' => 'this help message',
  299. '-o=file' => 'output the formatted code to "file"',
  300. ];
  301. $maxLen = max(array_map(function ($v) {
  302. return strlen($v);
  303. }, array_keys($options)));
  304. foreach ($options as $k => $v) {
  305. echo ' ', str_pad($k, $maxLen), ' ', $v, PHP_EOL;
  306. }
  307. echo PHP_EOL, 'If <target> is blank, it reads from stdin', PHP_EOL;
  308. die();
  309. }
  310. if (isset($opts['from']) && !isset($opts['to'])) {
  311. fwrite(STDERR, "Refactor must have --from and --to parameters" . PHP_EOL);
  312. exit(255);
  313. }
  314. $debug = false;
  315. $fmt = new CodeFormatter($debug);
  316. if (isset($opts['from']) && isset($opts['to'])) {
  317. $argv = array_values(
  318. array_filter($argv,
  319. function ($v) {
  320. $param_from = '--from';
  321. $param_to = '--to';
  322. return substr($v, 0, strlen($param_from)) !== $param_from && substr($v, 0, strlen($param_to)) !== $param_to;
  323. }
  324. )
  325. );
  326. $fmt->addPass(new RefactorPass($opts['from'], $opts['to']));
  327. }
  328. if (isset($opts['o'])) {
  329. unset($argv[1]);
  330. unset($argv[2]);
  331. $argv = array_values($argv);
  332. file_put_contents($opts['o'], $fmt->formatCode(file_get_contents($argv[1])));
  333. } elseif (isset($argv[1]) && is_file($argv[1])) {
  334. echo $fmt->formatCode(file_get_contents($argv[1]));
  335. } elseif (isset($argv[1]) && is_dir($argv[1])) {
  336. $dir = new RecursiveDirectoryIterator($argv[1]);
  337. $it = new RecursiveIteratorIterator($dir);
  338. $files = new RegexIterator($it, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH);
  339. foreach ($files as $file) {
  340. $file = $file[0];
  341. echo $file;
  342. file_put_contents($file . '-tmp', $fmt->formatCode(file_get_contents($file)));
  343. rename($file, $file . '~');
  344. rename($file . '-tmp', $file);
  345. echo PHP_EOL;
  346. }
  347. } else {
  348. echo $fmt->formatCode(file_get_contents('php://stdin'));
  349. }
  350. }