WhitespaceShell.php 2.1 KB

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