CodeShell.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <?php
  2. App::uses('AppShell', 'Console/Command');
  3. if (!defined('LF')) {
  4. define('LF', PHP_EOL); # use PHP to detect default linebreak
  5. }
  6. /**
  7. * Misc Code Fix Tools
  8. *
  9. * cake Tools.Code dependencies [-p PluginName] [-c /custom/path]
  10. * - Fix missing App::uses() statements
  11. *
  12. * @author Mark Scherer
  13. * @license MIT
  14. * 2012-07-19 ms
  15. */
  16. class CodeShell extends AppShell {
  17. protected $_files;
  18. protected $_paths;
  19. /**
  20. * detect and fix class dependencies
  21. * 2012-07-19 ms
  22. */
  23. public function dependencies() {
  24. if ($customPath = $this->params['custom']) {
  25. $this->_paths = array($customPath);
  26. } elseif (!empty($this->params['plugin'])) {
  27. $this->_paths = array(App::pluginPath($this->params['plugin']));
  28. } else {
  29. $this->_paths = array(APP);
  30. }
  31. $this->_findFiles('php');
  32. foreach ($this->_files as $file) {
  33. $this->out(__d('cake_console', 'Updating %s...', $file), 1, Shell::VERBOSE);
  34. $this->_correctFile($file);
  35. $this->out(__d('cake_console', 'Done updating %s', $file), 1, Shell::VERBOSE);
  36. }
  37. }
  38. protected function _correctFile($file) {
  39. $fileContent = $content = file_get_contents($file);
  40. preg_match_all('/class \w+ extends (.+)\s*{/', $fileContent, $matches);
  41. if (empty($matches)) {
  42. continue;
  43. }
  44. $excludes = array('Fixture', 'TestSuite', 'CakeTestModel');
  45. $missingClasses = array();
  46. foreach ($matches[1] as $match) {
  47. $match = trim($match);
  48. preg_match('/\bApp\:\:uses\(\''.$match.'\'/', $fileContent, $usesMatches);
  49. if (!empty($usesMatches)) {
  50. continue;
  51. }
  52. preg_match('/class '.$match.'\s*(w+)?{/', $fileContent, $existingMatches);
  53. if (!empty($existingMatches)) {
  54. continue;
  55. }
  56. if (in_array($match, $missingClasses)) {
  57. continue;
  58. }
  59. $break = false;
  60. foreach ($excludes as $exclude) {
  61. if (strposReverse($match, $exclude) === 0) {
  62. $break = true;
  63. break;
  64. }
  65. }
  66. if ($break) {
  67. continue;
  68. }
  69. $missingClasses[] = $match;
  70. }
  71. if (empty($missingClasses)) {
  72. return;
  73. }
  74. $fileContent = explode(LF, $fileContent);
  75. $inserted = array();
  76. $pos = 1;
  77. if (!empty($fileContent[1]) && $fileContent[1] == '/**') {
  78. for ($i = $pos; $i < count($fileContent)-1; $i++) {
  79. if (strpos($fileContent[$i], '*/') !== false) {
  80. if (strpos($fileContent[$i+1], 'class ') !== 0) {
  81. $pos = $i+1;
  82. }
  83. break;
  84. }
  85. }
  86. }
  87. # try to find the best position to insert app uses statements
  88. foreach ($fileContent as $row => $rowValue) {
  89. preg_match('/^App\:\:uses\(/', $rowValue, $matches);
  90. if ($matches) {
  91. $pos = $row;
  92. break;
  93. }
  94. }
  95. foreach ($missingClasses as $missingClass) {
  96. $classes = array(
  97. 'Controller' => 'Controller',
  98. 'Component' => 'Controller/Component',
  99. 'Shell' => 'Console/Command',
  100. 'Model' => 'Model',
  101. 'Behavior' => 'Model/Behavior',
  102. 'Datasource' => 'Model/Datasource',
  103. 'Task' => 'Console/Command/Task',
  104. 'View' => 'View',
  105. 'Helper' => 'View/Helper',
  106. );
  107. $type = null;
  108. foreach ($classes as $class => $namespace) {
  109. if (($t = strposReverse($missingClass, $class)) === 0) {
  110. $type = $namespace;
  111. break;
  112. }
  113. }
  114. if (empty($type)) {
  115. $this->err($missingClass.' ('.$file.') could not be matched');
  116. continue;
  117. }
  118. //FIXME
  119. if (!empty($this->params['plugin'])) {
  120. if ($class == 'Model') {
  121. $missingClassName = $missingClass;
  122. } else {
  123. $missingClassName = substr($missingClass, 0, strlen($missingClass) - strlen($class));
  124. }
  125. $objects = App::objects(($this->params['plugin'] ? $this->params['plugin'].'.' : '') . $class);
  126. if ($location = App::location($missingClass)) {
  127. $type = $location;
  128. echo(returns($type));
  129. } elseif (in_array($missingClass, $objects)) {
  130. $type = $this->params['plugin'] . '.' . $type;
  131. } else {
  132. $type = $type;
  133. }
  134. }
  135. $inserted[] = 'App::uses(\''.$missingClass.'\', \''.$type.'\');';
  136. }
  137. if (!$inserted) {
  138. return;
  139. }
  140. array_splice($fileContent, $pos, 0, $inserted);
  141. $fileContent = implode(LF, $fileContent);
  142. if (empty($this->params['dry-run'])) {
  143. file_put_contents($file, $fileContent);
  144. $this->out(__d('cake_console', 'Correcting %s', $file), 1, Shell::VERBOSE);
  145. }
  146. }
  147. /**
  148. * make sure all files are properly encoded (ü instead of &uuml; etc)
  149. * FIXME: non-utf8 files to utf8 files error on windows!
  150. *
  151. * 2012-01-06 ms
  152. */
  153. public function utf8() {
  154. $this->_paths = array(APP.'View'.DS);
  155. $this->params['ext'] = 'php|ctp';
  156. //$this->out('found: '.count($this->_files));
  157. $patterns = array(
  158. );
  159. $umlauts = array('ä', 'ö', 'ü', 'Ä', 'Ö', 'Ü', 'ß');
  160. foreach ($umlauts as $umlaut) {
  161. $patterns[] = array(
  162. ent($umlaut).' => '.$umlaut,
  163. '/'.ent($umlaut).'/',
  164. $umlaut,
  165. );
  166. }
  167. $this->_filesRegexpUpdate($patterns);
  168. }
  169. protected function _filesRegexpUpdate($patterns) {
  170. $this->_findFiles($this->params['ext']);
  171. foreach ($this->_files as $file) {
  172. $this->out(__d('cake_console', 'Updating %s...', $file), 1, Shell::VERBOSE);
  173. $this->_utf8File($file, $patterns);
  174. }
  175. }
  176. /**
  177. * Searches the paths and finds files based on extension.
  178. *
  179. * @param string $extensions
  180. * @return void
  181. */
  182. protected function _findFiles($extensions = '') {
  183. $this->_files = array();
  184. foreach ($this->_paths as $path) {
  185. if (!is_dir($path)) {
  186. continue;
  187. }
  188. $Iterator = new RegexIterator(
  189. new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)),
  190. '/^.+\.(' . $extensions . ')$/i',
  191. RegexIterator::MATCH
  192. );
  193. foreach ($Iterator as $file) {
  194. $excludes = array('Config');
  195. //Iterator processes plugins even if not asked to
  196. if (empty($this->params['plugin'])) {
  197. $excludes = am($excludes, array('Plugin', 'plugins'));
  198. }
  199. if (empty($this->params['vendor'])) {
  200. $excludes = am($excludes, array('Vendor', 'vendors'));
  201. }
  202. if (!empty($excludes)) {
  203. $isIllegalPluginPath = false;
  204. foreach ($excludes as $exclude) {
  205. if (strpos($file, $path . $exclude . DS) === 0) {
  206. $isIllegalPluginPath = true;
  207. break;
  208. }
  209. }
  210. if ($isIllegalPluginPath) {
  211. continue;
  212. }
  213. }
  214. if ($file->isFile()) {
  215. $this->_files[] = $file->getPathname();
  216. }
  217. }
  218. }
  219. }
  220. protected function _utf8File($file, $patterns) {
  221. $contents = $fileContent = file_get_contents($file);
  222. foreach ($patterns as $pattern) {
  223. $this->out(__d('cake_console', ' * Updating %s', $pattern[0]), 1, Shell::VERBOSE);
  224. $contents = preg_replace($pattern[1], $pattern[2], $contents);
  225. }
  226. $this->out(__d('cake_console', 'Done updating %s', $file), 1, Shell::VERBOSE);
  227. if (!$this->params['dry-run'] && $contents !== $fileContent) {
  228. if (file_exists($file)) {
  229. unlink($file);
  230. }
  231. if (WINDOWS) {
  232. //$fileContent = utf8_decode($fileContent);
  233. }
  234. file_put_contents($file, $contents);
  235. }
  236. }
  237. public function getOptionParser() {
  238. $subcommandParser = array(
  239. 'options' => array(
  240. 'plugin' => array(
  241. 'short' => 'p',
  242. 'help' => __d('cake_console', 'The plugin to update. Only the specified plugin will be updated.'),
  243. 'default' => ''
  244. ),
  245. 'custom' => array(
  246. 'short' => 'c',
  247. 'help' => __d('cake_console', 'Custom path to update recursivly.'),
  248. 'default' => ''
  249. ),
  250. 'ext' => array(
  251. 'short' => 'e',
  252. 'help' => __d('cake_console', 'The extension(s) to search. A pipe delimited list, or a preg_match compatible subpattern'),
  253. 'default' => 'php|ctp|thtml|inc|tpl'
  254. ),
  255. 'vendor'=> array(
  256. 'short' => 'e',
  257. 'help' => __d('cake_console', 'Include vendor files, as well'),
  258. 'boolean' => true
  259. ),
  260. 'dry-run'=> array(
  261. 'short' => 'd',
  262. 'help' => __d('cake_console', 'Dry run the update, no files will actually be modified.'),
  263. 'boolean' => true
  264. )
  265. )
  266. );
  267. return parent::getOptionParser()
  268. ->description(__d('cake_console', "A shell to help automate code cleanup. \n" .
  269. "Be sure to have a backup of your application before running these commands."))
  270. ->addSubcommand('group', array(
  271. 'help' => __d('cake_console', 'Run multiple upgrade commands.'),
  272. 'parser' => $subcommandParser
  273. ))
  274. ->addSubcommand('dependencies', array(
  275. 'help' => __d('cake_console', 'Correct dependencies'),
  276. 'parser' => $subcommandParser
  277. ))
  278. ->addSubcommand('utf8', array(
  279. 'help' => __d('cake_console', 'Make files utf8 compliant'),
  280. 'parser' => $subcommandParser
  281. ));
  282. }
  283. /** old stuff **/
  284. /**
  285. * Shell tasks
  286. *
  287. * @var array
  288. */
  289. public $tasks = array(
  290. 'CodeConvention',
  291. 'CodeWhitespace'
  292. );
  293. /**
  294. * Main execution function
  295. *
  296. * @return void
  297. */
  298. public function group() {
  299. if (!empty($this->args)) {
  300. if (!empty($this->args[1])) {
  301. $this->args[1] = constant($this->args[1]);
  302. } else {
  303. $this->args[1] = APP;
  304. }
  305. $this->{'Code'.ucfirst($this->args[0])}->execute($this->args[1]);
  306. } else {
  307. $this->out('Usage: cake code type');
  308. $this->out('');
  309. $this->out('type should be space-separated');
  310. $this->out('list of any combination of:');
  311. $this->out('');
  312. $this->out('convention');
  313. $this->out('whitespace');
  314. }
  315. }
  316. }
  317. function strposReverse($str, $search) {
  318. $str = strrev($str);
  319. $search = strrev($search);
  320. $posRev = strpos($str, $search);
  321. return $posRev;
  322. }