CodeCleanerTestCase.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. /*
  3. * This file is part of Psy Shell.
  4. *
  5. * (c) 2012-2017 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\PrettyPrinter\Standard as Printer;
  13. use Psy\CodeCleaner\CodeCleanerPass;
  14. use Psy\Exception\ParseErrorException;
  15. use Psy\ParserFactory;
  16. class CodeCleanerTestCase extends \PHPUnit_Framework_TestCase
  17. {
  18. protected $pass;
  19. protected $traverser;
  20. private $parser;
  21. private $printer;
  22. protected function setPass(CodeCleanerPass $pass)
  23. {
  24. $this->pass = $pass;
  25. if (!isset($this->traverser)) {
  26. $this->traverser = new NodeTraverser();
  27. }
  28. $this->traverser->addVisitor($this->pass);
  29. }
  30. protected function parse($code, $prefix = '<?php ')
  31. {
  32. $code = $prefix . $code;
  33. try {
  34. return $this->getParser()->parse($code);
  35. } catch (\PhpParser\Error $e) {
  36. if (!$this->parseErrorIsEOF($e)) {
  37. throw ParseErrorException::fromParseError($e);
  38. }
  39. try {
  40. // Unexpected EOF, try again with an implicit semicolon
  41. return $this->getParser()->parse($code . ';');
  42. } catch (\PhpParser\Error $e) {
  43. return false;
  44. }
  45. }
  46. }
  47. protected function traverse(array $stmts)
  48. {
  49. return $this->traverser->traverse($stmts);
  50. }
  51. protected function prettyPrint(array $stmts)
  52. {
  53. return $this->getPrinter()->prettyPrint($stmts);
  54. }
  55. protected function assertProcessesAs($from, $to)
  56. {
  57. $stmts = $this->parse($from);
  58. $stmts = $this->traverse($stmts);
  59. $this->assertEquals($to, $this->prettyPrint($stmts));
  60. }
  61. private function getParser()
  62. {
  63. if (!isset($this->parser)) {
  64. $parserFactory = new ParserFactory();
  65. $this->parser = $parserFactory->createParser();
  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. }