CodeCleanerTestCase.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /*
  3. * This file is part of Psy Shell.
  4. *
  5. * (c) 2012-2015 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\NodeTraverser;
  12. use PhpParser\Parser;
  13. use PhpParser\PrettyPrinter\Standard as Printer;
  14. use Psy\CodeCleaner\CodeCleanerPass;
  15. use Psy\Exception\ParseErrorException;
  16. use Psy\ParserFactory;
  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. $parserFactory = new ParserFactory();
  66. $this->parser = $parserFactory->createParser();
  67. }
  68. return $this->parser;
  69. }
  70. private function getPrinter()
  71. {
  72. if (!isset($this->printer)) {
  73. $this->printer = new Printer();
  74. }
  75. return $this->printer;
  76. }
  77. private function parseErrorIsEOF(\PhpParser\Error $e)
  78. {
  79. $msg = $e->getRawMessage();
  80. return ($msg === 'Unexpected token EOF') || (strpos($msg, 'Syntax error, unexpected EOF') !== false);
  81. }
  82. }