PrettyPrinterTest.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace PhpParser;
  3. use PhpParser\Node\Expr;
  4. use PhpParser\Node\Scalar\String_;
  5. use PhpParser\Node\Stmt;
  6. use PhpParser\PrettyPrinter\Standard;
  7. require_once __DIR__ . '/CodeTestAbstract.php';
  8. class PrettyPrinterTest extends CodeTestAbstract
  9. {
  10. protected function doTestPrettyPrintMethod($method, $name, $code, $dump) {
  11. $parser = new Parser(new Lexer\Emulative);
  12. $prettyPrinter = new Standard;
  13. $stmts = $parser->parse($code);
  14. $this->assertSame(
  15. $this->canonicalize($dump),
  16. $this->canonicalize($prettyPrinter->$method($stmts)),
  17. $name
  18. );
  19. }
  20. /**
  21. * @dataProvider provideTestPrettyPrint
  22. * @covers PhpParser\PrettyPrinter\Standard<extended>
  23. */
  24. public function testPrettyPrint($name, $code, $dump) {
  25. $this->doTestPrettyPrintMethod('prettyPrint', $name, $code, $dump);
  26. }
  27. /**
  28. * @dataProvider provideTestPrettyPrintFile
  29. * @covers PhpParser\PrettyPrinter\Standard<extended>
  30. */
  31. public function testPrettyPrintFile($name, $code, $dump) {
  32. $this->doTestPrettyPrintMethod('prettyPrintFile', $name, $code, $dump);
  33. }
  34. public function provideTestPrettyPrint() {
  35. return $this->getTests(__DIR__ . '/../code/prettyPrinter', 'test');
  36. }
  37. public function provideTestPrettyPrintFile() {
  38. return $this->getTests(__DIR__ . '/../code/prettyPrinter', 'file-test');
  39. }
  40. public function testPrettyPrintExpr() {
  41. $prettyPrinter = new Standard;
  42. $expr = new Expr\BinaryOp\Mul(
  43. new Expr\BinaryOp\Plus(new Expr\Variable('a'), new Expr\Variable('b')),
  44. new Expr\Variable('c')
  45. );
  46. $this->assertEquals('($a + $b) * $c', $prettyPrinter->prettyPrintExpr($expr));
  47. $expr = new Expr\Closure(array(
  48. 'stmts' => array(new Stmt\Return_(new String_("a\nb")))
  49. ));
  50. $this->assertEquals("function () {\n return 'a\nb';\n}", $prettyPrinter->prettyPrintExpr($expr));
  51. }
  52. }