Skip to content

Commit 0abe992

Browse files
committed
pretty printer: print file
1 parent 79277ea commit 0abe992

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

printer/printer.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,27 @@ func NewPrinter(w io.Writer, indentStr string) *Printer {
3030
}
3131
}
3232

33+
func (p *Printer) PrintFile(n *stmt.StmtList) {
34+
if len(n.Stmts) > 0 {
35+
firstStmt := n.Stmts[0]
36+
n.Stmts = n.Stmts[1:]
37+
38+
switch fs := firstStmt.(type) {
39+
case *stmt.InlineHtml:
40+
io.WriteString(p.w, fs.Value)
41+
io.WriteString(p.w, "<?php\n")
42+
default:
43+
io.WriteString(p.w, "<?php\n")
44+
p.printIndent()
45+
p.Print(fs)
46+
io.WriteString(p.w, "\n")
47+
}
48+
}
49+
p.indentDepth--
50+
p.printNodes(n.Stmts)
51+
io.WriteString(p.w, "\n")
52+
}
53+
3354
func (p *Printer) Print(n node.Node) {
3455
p.printNode(n)
3556
}

printer/printer_test.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,58 @@ import (
1515
"github.com/z7zmey/php-parser/printer"
1616
)
1717

18+
func TestPrintFile(t *testing.T) {
19+
o := bytes.NewBufferString("")
20+
21+
p := printer.NewPrinter(o, " ")
22+
p.PrintFile(&stmt.StmtList{
23+
Stmts: []node.Node{
24+
&stmt.Expression{Expr: &expr.Variable{VarName: &node.Identifier{Value: "a"}}},
25+
&stmt.Expression{Expr: &expr.Variable{VarName: &node.Identifier{Value: "b"}}},
26+
},
27+
})
28+
29+
expected := `<?php
30+
$a;
31+
$b;
32+
`
33+
actual := o.String()
34+
35+
if expected != actual {
36+
t.Errorf("\nexpected: %s\ngot: %s\n", expected, actual)
37+
}
38+
}
39+
40+
func TestPrintFileInlineHtml(t *testing.T) {
41+
o := bytes.NewBufferString("")
42+
43+
p := printer.NewPrinter(o, " ")
44+
p.PrintFile(&stmt.StmtList{
45+
Stmts: []node.Node{
46+
&stmt.InlineHtml{Value: "<div>HTML</div>"},
47+
&stmt.Expression{
48+
Expr: &scalar.Heredoc{
49+
Label: "\"LBL\"",
50+
Parts: []node.Node{
51+
&scalar.EncapsedStringPart{Value: "hello world\n"},
52+
},
53+
},
54+
},
55+
},
56+
})
57+
58+
expected := `<div>HTML</div><?php
59+
<<<"LBL"
60+
hello world
61+
LBL;
62+
`
63+
actual := o.String()
64+
65+
if expected != actual {
66+
t.Errorf("\nexpected: %s\ngot: %s\n", expected, actual)
67+
}
68+
}
69+
1870
// node
1971

2072
func TestPrintIdentifier(t *testing.T) {

0 commit comments

Comments
 (0)