pretty printer: print file

This commit is contained in:
z7zmey 2018-04-06 00:59:22 +03:00
parent 79277ea3cc
commit 0abe99274b
2 changed files with 73 additions and 0 deletions

View File

@ -30,6 +30,27 @@ func NewPrinter(w io.Writer, indentStr string) *Printer {
} }
} }
func (p *Printer) PrintFile(n *stmt.StmtList) {
if len(n.Stmts) > 0 {
firstStmt := n.Stmts[0]
n.Stmts = n.Stmts[1:]
switch fs := firstStmt.(type) {
case *stmt.InlineHtml:
io.WriteString(p.w, fs.Value)
io.WriteString(p.w, "<?php\n")
default:
io.WriteString(p.w, "<?php\n")
p.printIndent()
p.Print(fs)
io.WriteString(p.w, "\n")
}
}
p.indentDepth--
p.printNodes(n.Stmts)
io.WriteString(p.w, "\n")
}
func (p *Printer) Print(n node.Node) { func (p *Printer) Print(n node.Node) {
p.printNode(n) p.printNode(n)
} }

View File

@ -15,6 +15,58 @@ import (
"github.com/z7zmey/php-parser/printer" "github.com/z7zmey/php-parser/printer"
) )
func TestPrintFile(t *testing.T) {
o := bytes.NewBufferString("")
p := printer.NewPrinter(o, " ")
p.PrintFile(&stmt.StmtList{
Stmts: []node.Node{
&stmt.Expression{Expr: &expr.Variable{VarName: &node.Identifier{Value: "a"}}},
&stmt.Expression{Expr: &expr.Variable{VarName: &node.Identifier{Value: "b"}}},
},
})
expected := `<?php
$a;
$b;
`
actual := o.String()
if expected != actual {
t.Errorf("\nexpected: %s\ngot: %s\n", expected, actual)
}
}
func TestPrintFileInlineHtml(t *testing.T) {
o := bytes.NewBufferString("")
p := printer.NewPrinter(o, " ")
p.PrintFile(&stmt.StmtList{
Stmts: []node.Node{
&stmt.InlineHtml{Value: "<div>HTML</div>"},
&stmt.Expression{
Expr: &scalar.Heredoc{
Label: "\"LBL\"",
Parts: []node.Node{
&scalar.EncapsedStringPart{Value: "hello world\n"},
},
},
},
},
})
expected := `<div>HTML</div><?php
<<<"LBL"
hello world
LBL;
`
actual := o.String()
if expected != actual {
t.Errorf("\nexpected: %s\ngot: %s\n", expected, actual)
}
}
// node // node
func TestPrintIdentifier(t *testing.T) { func TestPrintIdentifier(t *testing.T) {