Drupal investigation

Fixer.php 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. <?php
  2. /**
  3. * A helper class for fixing errors.
  4. *
  5. * PHP version 5
  6. *
  7. * @category PHP
  8. * @package PHP_CodeSniffer
  9. * @author Greg Sherwood <gsherwood@squiz.net>
  10. * @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
  11. * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
  12. * @link http://pear.php.net/package/PHP_CodeSniffer
  13. */
  14. /**
  15. * A helper class for fixing errors.
  16. *
  17. * Provides helper functions that act upon a token array and modify the file
  18. * content.
  19. *
  20. * @category PHP
  21. * @package PHP_CodeSniffer
  22. * @author Greg Sherwood <gsherwood@squiz.net>
  23. * @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
  24. * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
  25. * @version Release: @package_version@
  26. * @link http://pear.php.net/package/PHP_CodeSniffer
  27. */
  28. class PHP_CodeSniffer_Fixer
  29. {
  30. /**
  31. * Is the fixer enabled and fixing a file?
  32. *
  33. * Sniffs should check this value to ensure they are not
  34. * doing extra processing to prepare for a fix when fixing is
  35. * not required.
  36. *
  37. * @var boolean
  38. */
  39. public $enabled = false;
  40. /**
  41. * The number of times we have looped over a file.
  42. *
  43. * @var int
  44. */
  45. public $loops = 0;
  46. /**
  47. * The file being fixed.
  48. *
  49. * @var PHP_CodeSniffer_File
  50. */
  51. private $_currentFile = null;
  52. /**
  53. * The list of tokens that make up the file contents.
  54. *
  55. * This is a simplified list which just contains the token content and nothing
  56. * else. This is the array that is updated as fixes are made, not the file's
  57. * token array. Imploding this array will give you the file content back.
  58. *
  59. * @var array(int => string)
  60. */
  61. private $_tokens = array();
  62. /**
  63. * A list of tokens that have already been fixed.
  64. *
  65. * We don't allow the same token to be fixed more than once each time
  66. * through a file as this can easily cause conflicts between sniffs.
  67. *
  68. * @var array(int)
  69. */
  70. private $_fixedTokens = array();
  71. /**
  72. * The last value of each fixed token.
  73. *
  74. * If a token is being "fixed" back to its last value, the fix is
  75. * probably conflicting with another.
  76. *
  77. * @var array(int => string)
  78. */
  79. private $_oldTokenValues = array();
  80. /**
  81. * A list of tokens that have been fixed during a changeset.
  82. *
  83. * All changes in changeset must be able to be applied, or else
  84. * the entire changeset is rejected.
  85. *
  86. * @var array()
  87. */
  88. private $_changeset = array();
  89. /**
  90. * Is there an open changeset.
  91. *
  92. * @var boolean
  93. */
  94. private $_inChangeset = false;
  95. /**
  96. * Is the current fixing loop in conflict?
  97. *
  98. * @var boolean
  99. */
  100. private $_inConflict = false;
  101. /**
  102. * The number of fixes that have been performed.
  103. *
  104. * @var int
  105. */
  106. private $_numFixes = 0;
  107. /**
  108. * Starts fixing a new file.
  109. *
  110. * @param PHP_CodeSniffer_File $phpcsFile The file being fixed.
  111. *
  112. * @return void
  113. */
  114. public function startFile($phpcsFile)
  115. {
  116. $this->_currentFile = $phpcsFile;
  117. $this->_numFixes = 0;
  118. $this->_fixedTokens = array();
  119. $tokens = $phpcsFile->getTokens();
  120. $this->_tokens = array();
  121. foreach ($tokens as $index => $token) {
  122. if (isset($token['orig_content']) === true) {
  123. $this->_tokens[$index] = $token['orig_content'];
  124. } else {
  125. $this->_tokens[$index] = $token['content'];
  126. }
  127. }
  128. }//end startFile()
  129. /**
  130. * Attempt to fix the file by processing it until no fixes are made.
  131. *
  132. * @return boolean
  133. */
  134. public function fixFile()
  135. {
  136. $fixable = $this->_currentFile->getFixableCount();
  137. if ($fixable === 0) {
  138. // Nothing to fix.
  139. return false;
  140. }
  141. $stdin = false;
  142. $cliValues = $this->_currentFile->phpcs->cli->getCommandLineValues();
  143. if (empty($cliValues['files']) === true) {
  144. $stdin = true;
  145. }
  146. $this->enabled = true;
  147. $this->loops = 0;
  148. while ($this->loops < 50) {
  149. ob_start();
  150. // Only needed once file content has changed.
  151. $contents = $this->getContents();
  152. if (PHP_CODESNIFFER_VERBOSITY > 2) {
  153. @ob_end_clean();
  154. echo '---START FILE CONTENT---'.PHP_EOL;
  155. $lines = explode($this->_currentFile->eolChar, $contents);
  156. $max = strlen(count($lines));
  157. foreach ($lines as $lineNum => $line) {
  158. $lineNum++;
  159. echo str_pad($lineNum, $max, ' ', STR_PAD_LEFT).'|'.$line.PHP_EOL;
  160. }
  161. echo '--- END FILE CONTENT ---'.PHP_EOL;
  162. ob_start();
  163. }
  164. $this->_inConflict = false;
  165. $this->_currentFile->refreshTokenListeners();
  166. $this->_currentFile->start($contents);
  167. ob_end_clean();
  168. $this->loops++;
  169. if (PHP_CODESNIFFER_CBF === true && $stdin === false) {
  170. echo "\r".str_repeat(' ', 80)."\r";
  171. echo "\t=> Fixing file: $this->_numFixes/$fixable violations remaining [made $this->loops pass";
  172. if ($this->loops > 1) {
  173. echo 'es';
  174. }
  175. echo ']... ';
  176. }
  177. if ($this->_numFixes === 0 && $this->_inConflict === false) {
  178. // Nothing left to do.
  179. break;
  180. } else if (PHP_CODESNIFFER_VERBOSITY > 1) {
  181. echo "\t* fixed $this->_numFixes violations, starting loop ".($this->loops + 1).' *'.PHP_EOL;
  182. }
  183. }//end while
  184. $this->enabled = false;
  185. if ($this->_numFixes > 0) {
  186. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  187. @ob_end_clean();
  188. echo "\t*** Reached maximum number of loops with $this->_numFixes violations left unfixed ***".PHP_EOL;
  189. ob_start();
  190. }
  191. return false;
  192. }
  193. return true;
  194. }//end fixFile()
  195. /**
  196. * Generates a text diff of the original file and the new content.
  197. *
  198. * @param string $filePath Optional file path to diff the file against.
  199. * If not specified, the original version of the
  200. * file will be used.
  201. * @param boolean $colors Print colored output or not.
  202. *
  203. * @return string
  204. */
  205. public function generateDiff($filePath=null, $colors=true)
  206. {
  207. if ($filePath === null) {
  208. $filePath = $this->_currentFile->getFilename();
  209. }
  210. $cwd = getcwd().DIRECTORY_SEPARATOR;
  211. if (strpos($filePath, $cwd) === 0) {
  212. $filename = substr($filePath, strlen($cwd));
  213. } else {
  214. $filename = $filePath;
  215. }
  216. $contents = $this->getContents();
  217. if (function_exists('sys_get_temp_dir') === true) {
  218. // This is needed for HHVM support, but only available from 5.2.1.
  219. $tempName = tempnam(sys_get_temp_dir(), 'phpcs-fixer');
  220. $fixedFile = fopen($tempName, 'w');
  221. } else {
  222. $fixedFile = tmpfile();
  223. $data = stream_get_meta_data($fixedFile);
  224. $tempName = $data['uri'];
  225. }
  226. fwrite($fixedFile, $contents);
  227. // We must use something like shell_exec() because whitespace at the end
  228. // of lines is critical to diff files.
  229. $filename = escapeshellarg($filename);
  230. $cmd = "diff -u -L$filename -LPHP_CodeSniffer $filename \"$tempName\"";
  231. $diff = shell_exec($cmd);
  232. fclose($fixedFile);
  233. if (is_file($tempName) === true) {
  234. unlink($tempName);
  235. }
  236. if ($colors === false) {
  237. return $diff;
  238. }
  239. $diffLines = explode(PHP_EOL, $diff);
  240. if (count($diffLines) === 1) {
  241. // Seems to be required for cygwin.
  242. $diffLines = explode("\n", $diff);
  243. }
  244. $diff = array();
  245. foreach ($diffLines as $line) {
  246. if (isset($line[0]) === true) {
  247. switch ($line[0]) {
  248. case '-':
  249. $diff[] = "\033[31m$line\033[0m";
  250. break;
  251. case '+':
  252. $diff[] = "\033[32m$line\033[0m";
  253. break;
  254. default:
  255. $diff[] = $line;
  256. }
  257. }
  258. }
  259. $diff = implode(PHP_EOL, $diff);
  260. return $diff;
  261. }//end generateDiff()
  262. /**
  263. * Get a count of fixes that have been performed on the file.
  264. *
  265. * This value is reset every time a new file is started, or an existing
  266. * file is restarted.
  267. *
  268. * @return int
  269. */
  270. public function getFixCount()
  271. {
  272. return $this->_numFixes;
  273. }//end getFixCount()
  274. /**
  275. * Get the current content of the file, as a string.
  276. *
  277. * @return string
  278. */
  279. public function getContents()
  280. {
  281. $contents = implode($this->_tokens);
  282. return $contents;
  283. }//end getContents()
  284. /**
  285. * Get the current fixed content of a token.
  286. *
  287. * This function takes changesets into account so should be used
  288. * instead of directly accessing the token array.
  289. *
  290. * @param int $stackPtr The position of the token in the token stack.
  291. *
  292. * @return string
  293. */
  294. public function getTokenContent($stackPtr)
  295. {
  296. if ($this->_inChangeset === true
  297. && isset($this->_changeset[$stackPtr]) === true
  298. ) {
  299. return $this->_changeset[$stackPtr];
  300. } else {
  301. return $this->_tokens[$stackPtr];
  302. }
  303. }//end getTokenContent()
  304. /**
  305. * Start recording actions for a changeset.
  306. *
  307. * @return void
  308. */
  309. public function beginChangeset()
  310. {
  311. if ($this->_inConflict === true) {
  312. return false;
  313. }
  314. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  315. $bt = debug_backtrace();
  316. $sniff = $bt[1]['class'];
  317. $line = $bt[0]['line'];
  318. @ob_end_clean();
  319. echo "\t=> Changeset started by $sniff (line $line)".PHP_EOL;
  320. ob_start();
  321. }
  322. $this->_changeset = array();
  323. $this->_inChangeset = true;
  324. }//end beginChangeset()
  325. /**
  326. * Stop recording actions for a changeset, and apply logged changes.
  327. *
  328. * @return boolean
  329. */
  330. public function endChangeset()
  331. {
  332. if ($this->_inConflict === true) {
  333. return false;
  334. }
  335. $this->_inChangeset = false;
  336. $success = true;
  337. $applied = array();
  338. foreach ($this->_changeset as $stackPtr => $content) {
  339. $success = $this->replaceToken($stackPtr, $content);
  340. if ($success === false) {
  341. break;
  342. } else {
  343. $applied[] = $stackPtr;
  344. }
  345. }
  346. if ($success === false) {
  347. // Rolling back all changes.
  348. foreach ($applied as $stackPtr) {
  349. $this->revertToken($stackPtr);
  350. }
  351. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  352. @ob_end_clean();
  353. echo "\t=> Changeset failed to apply".PHP_EOL;
  354. ob_start();
  355. }
  356. } else if (PHP_CODESNIFFER_VERBOSITY > 1) {
  357. $fixes = count($this->_changeset);
  358. @ob_end_clean();
  359. echo "\t=> Changeset ended: $fixes changes applied".PHP_EOL;
  360. ob_start();
  361. }
  362. $this->_changeset = array();
  363. }//end endChangeset()
  364. /**
  365. * Stop recording actions for a changeset, and discard logged changes.
  366. *
  367. * @return void
  368. */
  369. public function rollbackChangeset()
  370. {
  371. $this->_inChangeset = false;
  372. $this->_inConflict = false;
  373. if (empty($this->_changeset) === false) {
  374. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  375. $bt = debug_backtrace();
  376. if ($bt[1]['class'] === 'PHP_CodeSniffer_Fixer') {
  377. $sniff = $bt[2]['class'];
  378. $line = $bt[1]['line'];
  379. } else {
  380. $sniff = $bt[1]['class'];
  381. $line = $bt[0]['line'];
  382. }
  383. $numChanges = count($this->_changeset);
  384. @ob_end_clean();
  385. echo "\t\tR: $sniff (line $line) rolled back the changeset ($numChanges changes)".PHP_EOL;
  386. echo "\t=> Changeset rolled back".PHP_EOL;
  387. ob_start();
  388. }
  389. $this->_changeset = array();
  390. }//end if
  391. }//end rollbackChangeset()
  392. /**
  393. * Replace the entire contents of a token.
  394. *
  395. * @param int $stackPtr The position of the token in the token stack.
  396. * @param string $content The new content of the token.
  397. *
  398. * @return bool If the change was accepted.
  399. */
  400. public function replaceToken($stackPtr, $content)
  401. {
  402. if ($this->_inConflict === true) {
  403. return false;
  404. }
  405. if ($this->_inChangeset === false
  406. && isset($this->_fixedTokens[$stackPtr]) === true
  407. ) {
  408. $indent = "\t";
  409. if (empty($this->_changeset) === false) {
  410. $indent .= "\t";
  411. }
  412. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  413. @ob_end_clean();
  414. echo "$indent* token $stackPtr has already been modified, skipping *".PHP_EOL;
  415. ob_start();
  416. }
  417. return false;
  418. }
  419. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  420. $bt = debug_backtrace();
  421. if ($bt[1]['class'] === 'PHP_CodeSniffer_Fixer') {
  422. $sniff = $bt[2]['class'];
  423. $line = $bt[1]['line'];
  424. } else {
  425. $sniff = $bt[1]['class'];
  426. $line = $bt[0]['line'];
  427. }
  428. $tokens = $this->_currentFile->getTokens();
  429. $type = $tokens[$stackPtr]['type'];
  430. $oldContent = PHP_CodeSniffer::prepareForOutput($this->_tokens[$stackPtr]);
  431. $newContent = PHP_CodeSniffer::prepareForOutput($content);
  432. if (trim($this->_tokens[$stackPtr]) === '' && isset($this->_tokens[($stackPtr + 1)]) === true) {
  433. // Add some context for whitespace only changes.
  434. $append = PHP_CodeSniffer::prepareForOutput($this->_tokens[($stackPtr + 1)]);
  435. $oldContent .= $append;
  436. $newContent .= $append;
  437. }
  438. }//end if
  439. if ($this->_inChangeset === true) {
  440. $this->_changeset[$stackPtr] = $content;
  441. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  442. @ob_end_clean();
  443. echo "\t\tQ: $sniff (line $line) replaced token $stackPtr ($type) \"$oldContent\" => \"$newContent\"".PHP_EOL;
  444. ob_start();
  445. }
  446. return true;
  447. }
  448. if (isset($this->_oldTokenValues[$stackPtr]) === false) {
  449. $this->_oldTokenValues[$stackPtr] = array(
  450. 'curr' => $content,
  451. 'prev' => $this->_tokens[$stackPtr],
  452. 'loop' => $this->loops,
  453. );
  454. } else {
  455. if ($this->_oldTokenValues[$stackPtr]['prev'] === $content
  456. && $this->_oldTokenValues[$stackPtr]['loop'] === ($this->loops - 1)
  457. ) {
  458. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  459. $indent = "\t";
  460. if (empty($this->_changeset) === false) {
  461. $indent .= "\t";
  462. }
  463. $loop = $this->_oldTokenValues[$stackPtr]['loop'];
  464. @ob_end_clean();
  465. echo "$indent**** $sniff (line $line) has possible conflict with another sniff on loop $loop; caused by the following change ****".PHP_EOL;
  466. echo "$indent**** replaced token $stackPtr ($type) \"$oldContent\" => \"$newContent\" ****".PHP_EOL;
  467. }
  468. if ($this->_oldTokenValues[$stackPtr]['loop'] >= ($this->loops - 1)) {
  469. $this->_inConflict = true;
  470. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  471. echo "$indent**** ignoring all changes until next loop ****".PHP_EOL;
  472. }
  473. }
  474. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  475. ob_start();
  476. }
  477. return false;
  478. }//end if
  479. $this->_oldTokenValues[$stackPtr]['prev'] = $this->_oldTokenValues[$stackPtr]['curr'];
  480. $this->_oldTokenValues[$stackPtr]['curr'] = $content;
  481. $this->_oldTokenValues[$stackPtr]['loop'] = $this->loops;
  482. }//end if
  483. $this->_fixedTokens[$stackPtr] = $this->_tokens[$stackPtr];
  484. $this->_tokens[$stackPtr] = $content;
  485. $this->_numFixes++;
  486. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  487. $indent = "\t";
  488. if (empty($this->_changeset) === false) {
  489. $indent .= "\tA: ";
  490. }
  491. @ob_end_clean();
  492. echo "$indent$sniff (line $line) replaced token $stackPtr ($type) \"$oldContent\" => \"$newContent\"".PHP_EOL;
  493. ob_start();
  494. }
  495. return true;
  496. }//end replaceToken()
  497. /**
  498. * Reverts the previous fix made to a token.
  499. *
  500. * @param int $stackPtr The position of the token in the token stack.
  501. *
  502. * @return bool If a change was reverted.
  503. */
  504. public function revertToken($stackPtr)
  505. {
  506. if (isset($this->_fixedTokens[$stackPtr]) === false) {
  507. return false;
  508. }
  509. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  510. $bt = debug_backtrace();
  511. if ($bt[1]['class'] === 'PHP_CodeSniffer_Fixer') {
  512. $sniff = $bt[2]['class'];
  513. $line = $bt[1]['line'];
  514. } else {
  515. $sniff = $bt[1]['class'];
  516. $line = $bt[0]['line'];
  517. }
  518. $tokens = $this->_currentFile->getTokens();
  519. $type = $tokens[$stackPtr]['type'];
  520. $oldContent = PHP_CodeSniffer::prepareForOutput($this->_tokens[$stackPtr]);
  521. $newContent = PHP_CodeSniffer::prepareForOutput($this->_fixedTokens[$stackPtr]);
  522. if (trim($this->_tokens[$stackPtr]) === '' && isset($tokens[($stackPtr + 1)]) === true) {
  523. // Add some context for whitespace only changes.
  524. $append = PHP_CodeSniffer::prepareForOutput($this->_tokens[($stackPtr + 1)]);
  525. $oldContent .= $append;
  526. $newContent .= $append;
  527. }
  528. }//end if
  529. $this->_tokens[$stackPtr] = $this->_fixedTokens[$stackPtr];
  530. unset($this->_fixedTokens[$stackPtr]);
  531. $this->_numFixes--;
  532. if (PHP_CODESNIFFER_VERBOSITY > 1) {
  533. $indent = "\t";
  534. if (empty($this->_changeset) === false) {
  535. $indent .= "\tR: ";
  536. }
  537. @ob_end_clean();
  538. echo "$indent$sniff (line $line) reverted token $stackPtr ($type) \"$oldContent\" => \"$newContent\"".PHP_EOL;
  539. ob_start();
  540. }
  541. return true;
  542. }//end revertToken()
  543. /**
  544. * Replace the content of a token with a part of its current content.
  545. *
  546. * @param int $stackPtr The position of the token in the token stack.
  547. * @param int $start The first character to keep.
  548. * @param int $length The number of chacters to keep. If NULL, the content of
  549. * the token from $start to the end of the content is kept.
  550. *
  551. * @return bool If the change was accepted.
  552. */
  553. public function substrToken($stackPtr, $start, $length=null)
  554. {
  555. $current = $this->getTokenContent($stackPtr);
  556. if ($length === null) {
  557. $newContent = substr($current, $start);
  558. } else {
  559. $newContent = substr($current, $start, $length);
  560. }
  561. return $this->replaceToken($stackPtr, $newContent);
  562. }//end substrToken()
  563. /**
  564. * Adds a newline to end of a token's content.
  565. *
  566. * @param int $stackPtr The position of the token in the token stack.
  567. *
  568. * @return bool If the change was accepted.
  569. */
  570. public function addNewline($stackPtr)
  571. {
  572. $current = $this->getTokenContent($stackPtr);
  573. return $this->replaceToken($stackPtr, $current.$this->_currentFile->eolChar);
  574. }//end addNewline()
  575. /**
  576. * Adds a newline to the start of a token's content.
  577. *
  578. * @param int $stackPtr The position of the token in the token stack.
  579. *
  580. * @return bool If the change was accepted.
  581. */
  582. public function addNewlineBefore($stackPtr)
  583. {
  584. $current = $this->getTokenContent($stackPtr);
  585. return $this->replaceToken($stackPtr, $this->_currentFile->eolChar.$current);
  586. }//end addNewlineBefore()
  587. /**
  588. * Adds content to the end of a token's current content.
  589. *
  590. * @param int $stackPtr The position of the token in the token stack.
  591. * @param string $content The content to add.
  592. *
  593. * @return bool If the change was accepted.
  594. */
  595. public function addContent($stackPtr, $content)
  596. {
  597. $current = $this->getTokenContent($stackPtr);
  598. return $this->replaceToken($stackPtr, $current.$content);
  599. }//end addContent()
  600. /**
  601. * Adds content to the start of a token's current content.
  602. *
  603. * @param int $stackPtr The position of the token in the token stack.
  604. * @param string $content The content to add.
  605. *
  606. * @return bool If the change was accepted.
  607. */
  608. public function addContentBefore($stackPtr, $content)
  609. {
  610. $current = $this->getTokenContent($stackPtr);
  611. return $this->replaceToken($stackPtr, $content.$current);
  612. }//end addContentBefore()
  613. }//end class