CodeShell.php 9.2 KB

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