node: parse and requote php single-quoted strings

This commit is contained in:
mappu 2020-04-07 22:51:31 +12:00
parent 70021d7e6d
commit d6cd0e8191
2 changed files with 34 additions and 2 deletions

10
node.go
View File

@ -927,8 +927,14 @@ func (this *conversionState) convertNoFreeFloating(n_ node.Node) (string, error)
return n.Value, nil // number formats are compatible
case *scalar.String:
return n.Value, nil // It's already quoted in PHP format
// return strconv.Quote(n.Value), nil // Go source code quoting format
// We need to transform the string format - e.g. Go does not support
// single-quoted strings
rawValue, err := phpUnquote(n.Value)
if err != nil {
return "", parseErr{n, err}
}
return strconv.Quote(rawValue), nil // Go source code quoting format
//
//

26
quote.go Normal file
View File

@ -0,0 +1,26 @@
package main
import (
"errors"
"strconv"
"strings"
)
func phpUnquote(s string) (string, error) {
if len(s) == 0 {
return "", errors.New("expected quotes around string")
}
if s[0] == '"' {
// Quote system is similar enough to Go's that strconv will probably just work
return strconv.Unquote(s)
}
if s[0] == '\'' {
// Single-quotes escape fewer things
unSQuo := strings.NewReplacer(`\'`, `'`, `\\`, `\`)
return unSQuo.Replace(s[1 : len(s)-1]), nil
}
return "", errors.New("expected single/double quotes")
}