WhitespaceShell.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. App::uses('AppShell', 'Console/Command');
  3. App::uses('Folder', 'Utility');
  4. class WhitespaceShell extends AppShell {
  5. public $autoCorrectAll = false;
  6. # each report: [0] => found, [1] => corrected
  7. public $report = array('leading'=>array(0, 0),'trailing'=>array(0, 0));
  8. public function main() {
  9. $App = new Folder(APP);
  10. $r = $App->findRecursive('.*\.php');
  11. $this->out("Checking *.php in ".APP);
  12. $folders = array();
  13. foreach ($r as $file) {
  14. $error = '';
  15. $action = '';
  16. $c = file_get_contents($file);
  17. if (preg_match('/^[\n\r|\n\r|\n|\r|\s]+\<\?php/', $c)) {
  18. $error = 'leading';
  19. }
  20. if (preg_match('/\?\>[\n\r|\n\r|\n|\r|\s]+$/', $c)) {
  21. $error = 'trailing';
  22. }
  23. if (!empty($error)) {
  24. $this->report[$error][0]++;
  25. $this->out('');
  26. $this->out('contains '.$error.' whitespaces: '.$this->shortPath($file));
  27. if (!$this->autoCorrectAll) {
  28. $dirname = dirname($file);
  29. if (in_array($dirname, $folders)) {
  30. $action = 'y';
  31. }
  32. while (empty($action)) {
  33. //TODO: [r]!
  34. $action = $this->in(__('Remove? [y]/[n], [a] for all in this folder, [r] for all below, [*] for all files(!), [q] to quit'), array('y','n','r','a','q','*'), 'q');
  35. }
  36. } else {
  37. $action = 'y';
  38. }
  39. if ($action == '*') {
  40. $action = 'y';
  41. $this->autoCorrectAll = true;
  42. } elseif ($action == 'a') {
  43. $action = 'y';
  44. $folders[] = $dirname;
  45. $this->out('All: '.$dirname);
  46. }
  47. if ($action == 'q') {
  48. die('Abort... Done');
  49. } elseif ($action == 'y') {
  50. if ($error == 'leading') {
  51. $res = preg_replace('/^[\n\r|\n\r|\n|\r|\s]+\<\?php/', '<?php', $c);
  52. } else { //trailing
  53. $res = preg_replace('/\?\>[\n\r|\n\r|\n|\r|\s]+$/', '?>', $c);
  54. }
  55. file_put_contents($file, $res);
  56. $this->report[$error][1]++;
  57. $this->out('fixed '.$error.' whitespaces: '.$this->shortPath($file));
  58. }
  59. }
  60. }
  61. # report
  62. $this->out('--------');
  63. $this->out('found '.$this->report['leading'][0].' leading, '.$this->report['trailing'][0].' trailing ws');
  64. $this->out('fixed '.$this->report['leading'][1].' leading, '.$this->report['trailing'][1].' trailing ws');
  65. }
  66. }