No Description

CodeCleanerTestCase.php 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /*
  3. * This file is part of Psy Shell
  4. *
  5. * (c) 2012-2014 Justin Hileman
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Psy\Test\CodeCleaner;
  11. use PHPParser_Lexer as Lexer;
  12. use PHPParser_NodeTraverser as NodeTraverser;
  13. use PHPParser_Parser as Parser;
  14. use PHPParser_PrettyPrinter_Default as Printer;
  15. use Psy\CodeCleaner\CodeCleanerPass;
  16. use Psy\Exception\ParseErrorException;
  17. class CodeCleanerTestCase extends \PHPUnit_Framework_TestCase
  18. {
  19. protected $pass;
  20. protected $traverser;
  21. private $parser;
  22. private $printer;
  23. protected function setPass(CodeCleanerPass $pass)
  24. {
  25. $this->pass = $pass;
  26. if (!isset($this->traverser)) {
  27. $this->traverser = new NodeTraverser();
  28. }
  29. $this->traverser->addVisitor($this->pass);
  30. }
  31. protected function parse($code, $prefix = '<?php ')
  32. {
  33. $code = $prefix . $code;
  34. try {
  35. return $this->getParser()->parse($code);
  36. } catch (\PHPParser_Error $e) {
  37. if (!$this->parseErrorIsEOF($e)) {
  38. throw ParseErrorException::fromParseError($e);
  39. }
  40. try {
  41. // Unexpected EOF, try again with an implicit semicolon
  42. return $this->getParser()->parse($code . ';');
  43. } catch (\PHPParser_Error $e) {
  44. return false;
  45. }
  46. }
  47. }
  48. protected function traverse(array $stmts)
  49. {
  50. return $this->traverser->traverse($stmts);
  51. }
  52. protected function prettyPrint(array $stmts)
  53. {
  54. return $this->getPrinter()->prettyPrint($stmts);
  55. }
  56. protected function assertProcessesAs($from, $to)
  57. {
  58. $stmts = $this->parse($from);
  59. $stmts = $this->traverse($stmts);
  60. $this->assertEquals($to, $this->prettyPrint($stmts));
  61. }
  62. private function getParser()
  63. {
  64. if (!isset($this->parser)) {
  65. $this->parser = new Parser(new Lexer());
  66. }
  67. return $this->parser;
  68. }
  69. private function getPrinter()
  70. {
  71. if (!isset($this->printer)) {
  72. $this->printer = new Printer();
  73. }
  74. return $this->printer;
  75. }
  76. private function parseErrorIsEOF(\PHPParser_Error $e)
  77. {
  78. $msg = $e->getRawMessage();
  79. return ($msg === "Unexpected token EOF") || (strpos($msg, "Syntax error, unexpected EOF") !== false);
  80. }
  81. }