CodeShell.php 9.4 KB

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