CodeShell.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. */
  15. class CodeShell extends AppShell {
  16. protected $_files;
  17. protected $_paths;
  18. /**
  19. * Detect and fix class dependencies
  20. *
  21. * @return void
  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. $count = count($fileContent);
  79. for ($i = $pos; $i < $count - 1; $i++) {
  80. if (strpos($fileContent[$i], '*/') !== false) {
  81. if (strpos($fileContent[$i + 1], 'class ') !== 0) {
  82. $pos = $i + 1;
  83. }
  84. break;
  85. }
  86. }
  87. }
  88. # try to find the best position to insert app uses statements
  89. foreach ($fileContent as $row => $rowValue) {
  90. preg_match('/^App\:\:uses\(/', $rowValue, $matches);
  91. if ($matches) {
  92. $pos = $row;
  93. break;
  94. }
  95. }
  96. foreach ($missingClasses as $missingClass) {
  97. $classes = array(
  98. 'Controller' => 'Controller',
  99. 'Component' => 'Controller/Component',
  100. 'Shell' => 'Console/Command',
  101. 'Model' => 'Model',
  102. 'Behavior' => 'Model/Behavior',
  103. 'Datasource' => 'Model/Datasource',
  104. 'Task' => 'Console/Command/Task',
  105. 'View' => 'View',
  106. 'Helper' => 'View/Helper',
  107. );
  108. $type = null;
  109. foreach ($classes as $class => $namespace) {
  110. if (($t = strposReverse($missingClass, $class)) === 0) {
  111. $type = $namespace;
  112. break;
  113. }
  114. }
  115. if (empty($type)) {
  116. $this->err($missingClass . ' (' . $file . ') could not be matched');
  117. continue;
  118. }
  119. if ($class === 'Model') {
  120. $missingClassName = $missingClass;
  121. } else {
  122. $missingClassName = substr($missingClass, 0, strlen($missingClass) - strlen($class));
  123. }
  124. $objects = App::objects(($this->params['plugin'] ? $this->params['plugin'] . '.' : '') . $class);
  125. //FIXME: correct result for plugin classes
  126. if ($missingClass === 'Component') {
  127. $type = 'Controller';
  128. } elseif ($missingClass === 'Helper') {
  129. $type = 'View';
  130. } elseif ($missingClass === 'ModelBehavior') {
  131. $type = 'Model';
  132. } elseif (!empty($this->params['plugin']) && ($location = App::location($missingClass))) {
  133. $type = $location;
  134. } elseif (in_array($missingClass, $objects)) {
  135. $type = ($this->params['plugin'] ? ($this->params['plugin'] . '.') : '') . $type;
  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. * @return void
  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. /**
  172. * CodeShell::_filesRegexpUpdate()
  173. *
  174. * @param mixed $patterns
  175. * @return void
  176. */
  177. protected function _filesRegexpUpdate($patterns) {
  178. $this->_findFiles($this->params['ext']);
  179. foreach ($this->_files as $file) {
  180. $this->out(__d('cake_console', 'Updating %s...', $file), 1, Shell::VERBOSE);
  181. $this->_utf8File($file, $patterns);
  182. }
  183. }
  184. /**
  185. * Searches the paths and finds files based on extension.
  186. *
  187. * @param string $extensions
  188. * @return void
  189. */
  190. protected function _findFiles($extensions = '') {
  191. $this->_files = array();
  192. foreach ($this->_paths as $path) {
  193. if (!is_dir($path)) {
  194. continue;
  195. }
  196. $Iterator = new RegexIterator(
  197. new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)),
  198. '/^.+\.(' . $extensions . ')$/i',
  199. RegexIterator::MATCH
  200. );
  201. foreach ($Iterator as $file) {
  202. $excludes = array('Config');
  203. //Iterator processes plugins even if not asked to
  204. if (empty($this->params['plugin'])) {
  205. $excludes = array_merge($excludes, array('Plugin', 'plugins'));
  206. }
  207. if (empty($this->params['vendor'])) {
  208. $excludes = array_merge($excludes, array('Vendor', 'vendors'));
  209. }
  210. if (!empty($excludes)) {
  211. $isIllegalPluginPath = false;
  212. foreach ($excludes as $exclude) {
  213. if (strpos($file, $path . $exclude . DS) === 0) {
  214. $isIllegalPluginPath = true;
  215. break;
  216. }
  217. }
  218. if ($isIllegalPluginPath) {
  219. continue;
  220. }
  221. }
  222. if ($file->isFile()) {
  223. $this->_files[] = $file->getPathname();
  224. }
  225. }
  226. }
  227. }
  228. /**
  229. * CodeShell::_utf8File()
  230. *
  231. * @param mixed $file
  232. * @param mixed $patterns
  233. * @return void
  234. */
  235. protected function _utf8File($file, $patterns) {
  236. $contents = $fileContent = file_get_contents($file);
  237. foreach ($patterns as $pattern) {
  238. $this->out(__d('cake_console', ' * Updating %s', $pattern[0]), 1, Shell::VERBOSE);
  239. $contents = preg_replace($pattern[1], $pattern[2], $contents);
  240. }
  241. $this->out(__d('cake_console', 'Done updating %s', $file), 1, Shell::VERBOSE);
  242. if (!$this->params['dry-run'] && $contents !== $fileContent) {
  243. if (file_exists($file)) {
  244. unlink($file);
  245. }
  246. if (WINDOWS) {
  247. //$fileContent = utf8_decode($fileContent);
  248. }
  249. file_put_contents($file, $contents);
  250. }
  251. }
  252. public function getOptionParser() {
  253. $subcommandParser = array(
  254. 'options' => array(
  255. 'plugin' => array(
  256. 'short' => 'p',
  257. 'help' => __d('cake_console', 'The plugin to update. Only the specified plugin will be updated.'),
  258. 'default' => ''
  259. ),
  260. 'custom' => array(
  261. 'short' => 'c',
  262. 'help' => __d('cake_console', 'Custom path to update recursivly.'),
  263. 'default' => ''
  264. ),
  265. 'ext' => array(
  266. 'short' => 'e',
  267. 'help' => __d('cake_console', 'The extension(s) to search. A pipe delimited list, or a preg_match compatible subpattern'),
  268. 'default' => 'php|ctp|thtml|inc|tpl'
  269. ),
  270. 'vendor' => array(
  271. 'short' => 'e',
  272. 'help' => __d('cake_console', 'Include vendor files, as well'),
  273. 'boolean' => true
  274. ),
  275. 'dry-run' => array(
  276. 'short' => 'd',
  277. 'help' => __d('cake_console', 'Dry run the update, no files will actually be modified.'),
  278. 'boolean' => true
  279. )
  280. )
  281. );
  282. return parent::getOptionParser()
  283. ->description(__d('cake_console', "A shell to help automate code cleanup. \n" .
  284. "Be sure to have a backup of your application before running these commands."))
  285. ->addSubcommand('group', array(
  286. 'help' => __d('cake_console', 'Run multiple commands.'),
  287. 'parser' => $subcommandParser
  288. ))
  289. ->addSubcommand('dependencies', array(
  290. 'help' => __d('cake_console', 'Correct dependencies'),
  291. 'parser' => $subcommandParser
  292. ))
  293. ->addSubcommand('utf8', array(
  294. 'help' => __d('cake_console', 'Make files utf8 compliant'),
  295. 'parser' => $subcommandParser
  296. ));
  297. }
  298. /**
  299. * Shell tasks
  300. *
  301. * @var array
  302. */
  303. public $tasks = array(
  304. 'CodeConvention',
  305. 'CodeWhitespace'
  306. );
  307. /**
  308. * Main execution function
  309. *
  310. * @return void
  311. */
  312. public function group() {
  313. if (!empty($this->args)) {
  314. if (!empty($this->args[1])) {
  315. $this->args[1] = constant($this->args[1]);
  316. } else {
  317. $this->args[1] = APP;
  318. }
  319. $this->{'Code' . ucfirst($this->args[0])}->execute($this->args[1]);
  320. } else {
  321. $this->out('Usage: cake code type');
  322. $this->out('');
  323. $this->out('type should be space-separated');
  324. $this->out('list of any combination of:');
  325. $this->out('');
  326. $this->out('convention');
  327. $this->out('whitespace');
  328. }
  329. }
  330. }
  331. function strposReverse($str, $search) {
  332. $str = strrev($str);
  333. $search = strrev($search);
  334. $posRev = strpos($str, $search);
  335. return $posRev;
  336. }