Skip to content

Commit 79277ea

Browse files
committed
pretty printer: print Heredoc
1 parent 9a799fc commit 79277ea

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

printer/printer.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package printer
22

33
import (
44
"io"
5+
"strings"
56

67
"github.com/z7zmey/php-parser/node/stmt"
78

@@ -99,6 +100,8 @@ func (p *Printer) printNode(n node.Node) {
99100
p.printScalarEncapsedStringPart(n)
100101
case *scalar.Encapsed:
101102
p.printScalarEncapsed(n)
103+
case *scalar.Heredoc:
104+
p.printScalarHeredoc(n)
102105
case *scalar.MagicConstant:
103106
p.printScalarMagicConstant(n)
104107

@@ -530,6 +533,20 @@ func (p *Printer) printScalarEncapsed(n node.Node) {
530533
io.WriteString(p.w, "\"")
531534
}
532535

536+
func (p *Printer) printScalarHeredoc(n node.Node) {
537+
nn := n.(*scalar.Heredoc)
538+
539+
io.WriteString(p.w, "<<<")
540+
io.WriteString(p.w, nn.Label)
541+
io.WriteString(p.w, "\n")
542+
543+
for _, nn := range nn.Parts {
544+
p.Print(nn)
545+
}
546+
547+
io.WriteString(p.w, strings.Trim(nn.Label, "\"'"))
548+
}
549+
533550
func (p *Printer) printScalarMagicConstant(n node.Node) {
534551
v := n.(*scalar.MagicConstant).Value
535552
io.WriteString(p.w, v)

printer/printer_test.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,50 @@ func TestPrintScalarEncapsed(t *testing.T) {
258258
}
259259
}
260260

261+
func TestPrintScalarHeredoc(t *testing.T) {
262+
o := bytes.NewBufferString("")
263+
264+
p := printer.NewPrinter(o, " ")
265+
p.Print(&scalar.Heredoc{
266+
Label: "LBL",
267+
Parts: []node.Node{
268+
&scalar.EncapsedStringPart{Value: "hello "},
269+
&expr.Variable{VarName: &node.Identifier{Value: "var"}},
270+
&scalar.EncapsedStringPart{Value: " world\n"},
271+
},
272+
})
273+
274+
expected := `<<<LBL
275+
hello $var world
276+
LBL`
277+
actual := o.String()
278+
279+
if expected != actual {
280+
t.Errorf("\nexpected: %s\ngot: %s\n", expected, actual)
281+
}
282+
}
283+
284+
func TestPrintScalarNowdoc(t *testing.T) {
285+
o := bytes.NewBufferString("")
286+
287+
p := printer.NewPrinter(o, " ")
288+
p.Print(&scalar.Heredoc{
289+
Label: "'LBL'",
290+
Parts: []node.Node{
291+
&scalar.EncapsedStringPart{Value: "hello world\n"},
292+
},
293+
})
294+
295+
expected := `<<<'LBL'
296+
hello world
297+
LBL`
298+
actual := o.String()
299+
300+
if expected != actual {
301+
t.Errorf("\nexpected: %s\ngot: %s\n", expected, actual)
302+
}
303+
}
304+
261305
func TestPrintScalarMagicConstant(t *testing.T) {
262306
o := bytes.NewBufferString("")
263307

0 commit comments

Comments
 (0)