From f18070853c4c82247ec8e153dbf2a4a1b43e730d Mon Sep 17 00:00:00 2001 From: Kevin Chabowski Date: Sun, 20 Oct 2013 16:21:03 +0200 Subject: Added function to tidy up the AST --- stupid_template_engine.php | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/stupid_template_engine.php b/stupid_template_engine.php index c67b1fd..840e0ce 100644 --- a/stupid_template_engine.php +++ b/stupid_template_engine.php @@ -211,7 +211,50 @@ class Parser { self::ESCAPES_DEFAULT, /* Escapes */ self::PARSE_SHORT | self::PARSE_TAG /* Flags */ ); - return $res[0]; + return self::tidyup_ast($res[0]); + } + + private static function tidyup_ast($ast) { + $out = array(); + + $prevtext = NULL; + $first = true; + foreach($ast as $node) { + if($node instanceof TagNode) { + $node->sub = self::tidyup_ast($node->sub); + } + + if(!($node instanceof TextNode)) { + if($prevtext !== NULL) { + if($prevtext->text != "") { + $out[] = $prevtext; + } + $prevtext = NULL; + } + + $out[] = $node; + + $first = false; + continue; + } + + if($first) { + $node->text = ltrim($node->text); + } + + if($prevtext !== NULL) { + $prevtext->text .= $node->text; + } else { + $prevtext = $node; + } + + $first = false; + } + + if(($prevtext !== NULL) && ($prevtext->text != "")) { + $out[] = $prevtext; + } + return $out; } private function parse_text($escapes, $flags, $breakon = NULL, $separator = NULL, $nullaction = NULL, $opentag = NULL, $openedat = -1) { -- cgit v1.2.3-70-g09d2