-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathParamFormatter.go
85 lines (73 loc) · 1.76 KB
/
ParamFormatter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package docxplate
import (
"bytes"
"strings"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
// Format - how to format an element
const (
FormatLower = ":lower"
FormatUpper = ":upper"
FormatTitle = ":title"
FormatCapitalize = ":capitalize"
)
// ParamFormatter ..
type ParamFormatter struct {
raw string
Format string
}
// NewFormatter - take raw ":empty:remove:list" and make formatter and its fields from it
func NewFormatter(raw []byte) *ParamFormatter {
raw = bytes.TrimSpace(raw)
raw = bytes.ToLower(raw)
// init with defaults
f := &ParamFormatter{
raw: string(raw),
}
// Always must start with ":"
if !strings.HasPrefix(f.raw, ":") {
return nil
}
// Remove the first ":" so split parts counting is more readable
// Split into parts
parts := strings.Split(f.raw[1:], ":")
for _, part := range parts {
switch part {
case "lower", "upper", "title", "capitalize":
f.Format = ":" + part
}
}
return f
}
// ApplyFormat - apply formatting to the given content based on the formatter
func (p *ParamFormatter) ApplyFormat(format string, content []byte) []byte {
switch format {
case FormatLower:
return bytes.ToLower(content)
case FormatUpper:
return bytes.ToUpper(content)
case FormatTitle:
titleCaser := cases.Title(language.Und)
return []byte(titleCaser.String(string(content)))
case FormatCapitalize:
content = bytes.TrimSpace(content)
if len(content) > 0 {
content[0] = bytes.ToUpper([]byte{content[0]})[0]
if len(content) > 1 {
content = append([]byte{content[0]}, bytes.ToLower(content[1:])...)
}
}
return content
default:
return content
}
}
// String - return rebuilt formatter string
func (p *ParamFormatter) String() string {
if p == nil {
return ""
}
s := p.Format
return s
}