CodeShell.php 8.5 KB

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