From 684a638f4610146b69e9553be2b724021b31318e Mon Sep 17 00:00:00 2001 From: nikic Date: Thu, 4 Aug 2011 18:19:45 +0200 Subject: [PATCH] Add possibility to pretty print expressions to PrettyPrinter --- README.md | 4 ++- lib/PHPParser/PrettyPrinterAbstract.php | 43 ++++++++++++++++--------- 2 files changed, 31 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 11838ad..36dd46d 100644 --- a/README.md +++ b/README.md @@ -153,4 +153,6 @@ For the code mentioned in the above section this should create the output: { echo $msg, "\n"; } - printLine('Hallo World!!!'); \ No newline at end of file + printLine('Hallo World!!!'); + +You can also pretty print only a single expression using the `prettyPrintExpr()` method. \ No newline at end of file diff --git a/lib/PHPParser/PrettyPrinterAbstract.php b/lib/PHPParser/PrettyPrinterAbstract.php index b2eda38..5e3122c 100644 --- a/lib/PHPParser/PrettyPrinterAbstract.php +++ b/lib/PHPParser/PrettyPrinterAbstract.php @@ -59,25 +59,30 @@ abstract class PHPParser_PrettyPrinterAbstract 'Expr_LogicalOr' => 18, ); protected $stmtsWithoutSemicolon = array( - 'Stmt_Func' => true, - 'Stmt_Interface' => true, - 'Stmt_Class' => true, - 'Stmt_ClassMethod' => true, - 'Stmt_For' => true, - 'Stmt_Foreach' => true, - 'Stmt_If' => true, - 'Stmt_Switch' => true, - 'Stmt_While' => true, - 'Stmt_TryCatch' => true, - 'Stmt_Label' => true, + 'Stmt_Func' => true, + 'Stmt_Interface' => true, + 'Stmt_Class' => true, + 'Stmt_ClassMethod' => true, + 'Stmt_For' => true, + 'Stmt_Foreach' => true, + 'Stmt_If' => true, + 'Stmt_Switch' => true, + 'Stmt_While' => true, + 'Stmt_TryCatch' => true, + 'Stmt_Label' => true, 'Stmt_HaltCompiler' => true, - 'Stmt_Namespace' => true, + 'Stmt_Namespace' => true, ); protected $precedenceStack; protected $precedenceStackPos; protected $noIndentToken; + public function __construct() { + $this->precedenceStack = array($this->precedenceStackPos = 0 => 19); + $this->noIndentToken = uniqid('_NO_INDENT_'); + } + /** * Pretty prints an array of nodes (statements). * @@ -86,12 +91,20 @@ abstract class PHPParser_PrettyPrinterAbstract * @return string Pretty printed nodes */ public function prettyPrint(array $nodes) { - $this->precedenceStack = array($this->precedenceStackPos = 0 => 19); - $this->noIndentToken = uniqid('_NO_INDENT_'); - return str_replace("\n" . $this->noIndentToken, "\n", $this->pStmts($nodes, false)); } + /** + * Pretty prints an expression. + * + * @param PHPParser_Node_Expr $node Expression node + * + * @return string Pretty printed node + */ + public function prettyPrintExpr(PHPParser_Node_Expr $node) { + return str_replace("\n" . $this->noIndentToken, "\n", $this->p($node)); + } + /** * Pretty prints an array of nodes (statements) and indents them optionally. *