CodeShell.php 9.0 KB

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