CodeShell.php 9.1 KB

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