translator.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. package ut
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "github.com/go-playground/locales"
  7. )
  8. const (
  9. paramZero = "{0}"
  10. paramOne = "{1}"
  11. unknownTranslation = ""
  12. )
  13. // Translator is universal translators
  14. // translator instance which is a thin wrapper
  15. // around locales.Translator instance providing
  16. // some extra functionality
  17. type Translator interface {
  18. locales.Translator
  19. // adds a normal translation for a particular language/locale
  20. // {#} is the only replacement type accepted and are add infintium
  21. // eg. one: '{0} day left' other: '{0} days left'
  22. Add(key interface{}, text string)
  23. // adds a cardinal plural translation for a particular language/locale
  24. // {0} is the only replacement type accepted and only one variable is accepted as
  25. // multiple cannot be used for a plural rule determination, unless it is a range;
  26. // see AddRange below.
  27. // eg. in locale 'en' one: '{0} day left' other: '{0} days left'
  28. AddCardinal(key interface{}, text string, rule locales.PluralRule) error
  29. // adds an ordinal plural translation for a particular language/locale
  30. // {0} is the only replacement type accepted and only one variable is accepted as
  31. // multiple cannot be used for a plural rule determination, unless it is a range;
  32. // see AddRange below.
  33. // eg. in locale 'en' one: '{0}st day of spring' other: '{0}nd day of spring'
  34. // - 1st, 2nd, 3rd...
  35. AddOrdinal(key interface{}, text string, rule locales.PluralRule) error
  36. // adds a range plural translation for a particular language/locale
  37. // {0} and {1} are the only replacement types accepted and only these are accepted.
  38. // eg. in locale 'nl' one: '{0}-{1} day left' other: '{0}-{1} days left'
  39. AddRange(key interface{}, text string, rule locales.PluralRule) error
  40. // creates the translation for the locale given the 'key' and params passed in
  41. T(key interface{}, params ...string) string
  42. // creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments
  43. // and param passed in
  44. C(key interface{}, num float64, digits uint64, param string) (string, error)
  45. // creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments
  46. // and param passed in
  47. O(key interface{}, num float64, digits uint64, param string) (string, error)
  48. // creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and
  49. // 'digit2' arguments and 'param1' and 'param2' passed in
  50. R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error)
  51. // VerifyTranslations checks to ensures that no plural rules have been
  52. // missed within the translations.
  53. VerifyTranslations() error
  54. }
  55. var _ Translator = new(translator)
  56. var _ locales.Translator = new(translator)
  57. type translator struct {
  58. locales.Translator
  59. translations map[interface{}]*transText
  60. cardinalTanslations map[interface{}][]*transText // array index is mapped to locales.PluralRule index + the locales.PluralRuleUnknown
  61. ordinalTanslations map[interface{}][]*transText
  62. rangeTanslations map[interface{}][]*transText
  63. }
  64. type transText struct {
  65. text string
  66. indexes []int
  67. }
  68. func newTranslator(trans locales.Translator) Translator {
  69. return &translator{
  70. Translator: trans,
  71. translations: make(map[interface{}]*transText), // translation text broken up by byte index
  72. cardinalTanslations: make(map[interface{}][]*transText),
  73. ordinalTanslations: make(map[interface{}][]*transText),
  74. rangeTanslations: make(map[interface{}][]*transText),
  75. }
  76. }
  77. // Add adds a normal translation for a particular language/locale
  78. // {#} is the only replacement type accepted and are add infintium
  79. // eg. one: '{0} day left' other: '{0} days left'
  80. func (t *translator) Add(key interface{}, text string) {
  81. trans := &transText{
  82. text: text,
  83. }
  84. var i int
  85. var idx int
  86. var cum int
  87. for {
  88. s := "{" + strconv.Itoa(i) + "}"
  89. idx = strings.Index(text[idx:], s)
  90. if idx == -1 {
  91. break
  92. }
  93. trans.indexes = append(trans.indexes, idx+cum)
  94. idx += len(s)
  95. trans.indexes = append(trans.indexes, idx+cum)
  96. cum += idx
  97. i++
  98. }
  99. t.translations[key] = trans
  100. }
  101. // AddCardinal adds a cardinal plural translation for a particular language/locale
  102. // {0} is the only replacement type accepted and only one variable is accepted as
  103. // multiple cannot be used for a plural rule determination, unless it is a range;
  104. // see AddRange below.
  105. // eg. in locale 'en' one: '{0} day left' other: '{0} days left'
  106. func (t *translator) AddCardinal(key interface{}, text string, rule locales.PluralRule) error {
  107. tarr, ok := t.cardinalTanslations[key]
  108. if ok {
  109. // verify not adding a conflicting record
  110. if len(tarr) > 0 && tarr[rule] != nil {
  111. return &ErrConflictingTranslation{key: key, rule: rule, text: text}
  112. }
  113. } else {
  114. tarr = make([]*transText, 7, 7)
  115. // tarr = make([]*transText, len(t.PluralsCardinal())+1, len(t.PluralsCardinal())+1)
  116. t.cardinalTanslations[key] = tarr
  117. }
  118. trans := &transText{
  119. text: text,
  120. indexes: make([]int, 2, 2),
  121. }
  122. tarr[rule] = trans
  123. idx := strings.Index(text, paramZero)
  124. if idx == -1 {
  125. tarr[rule] = nil
  126. return &ErrCardinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddCardinal'", paramZero)}
  127. }
  128. trans.indexes[0] = idx
  129. trans.indexes[1] = idx + len(paramZero)
  130. return nil
  131. }
  132. // AddOrdinal adds an ordinal plural translation for a particular language/locale
  133. // {0} is the only replacement type accepted and only one variable is accepted as
  134. // multiple cannot be used for a plural rule determination, unless it is a range;
  135. // see AddRange below.
  136. // eg. in locale 'en' one: '{0}st day of spring' other: '{0}nd day of spring' - 1st, 2nd, 3rd...
  137. func (t *translator) AddOrdinal(key interface{}, text string, rule locales.PluralRule) error {
  138. tarr, ok := t.ordinalTanslations[key]
  139. if ok {
  140. // verify not adding a conflicting record
  141. if len(tarr) > 0 && tarr[rule] != nil {
  142. return &ErrConflictingTranslation{key: key, rule: rule, text: text}
  143. }
  144. } else {
  145. tarr = make([]*transText, 7, 7)
  146. t.ordinalTanslations[key] = tarr
  147. }
  148. trans := &transText{
  149. text: text,
  150. indexes: make([]int, 2, 2),
  151. }
  152. tarr[rule] = trans
  153. idx := strings.Index(text, paramZero)
  154. if idx == -1 {
  155. tarr[rule] = nil
  156. return &ErrOrdinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddOrdinal'", paramZero)}
  157. }
  158. trans.indexes[0] = idx
  159. trans.indexes[1] = idx + len(paramZero)
  160. return nil
  161. }
  162. // AddRange adds a range plural translation for a particular language/locale
  163. // {0} and {1} are the only replacement types accepted and only these are accepted.
  164. // eg. in locale 'nl' one: '{0}-{1} day left' other: '{0}-{1} days left'
  165. func (t *translator) AddRange(key interface{}, text string, rule locales.PluralRule) error {
  166. tarr, ok := t.rangeTanslations[key]
  167. if ok {
  168. // verify not adding a conflicting record
  169. if len(tarr) > 0 && tarr[rule] != nil {
  170. return &ErrConflictingTranslation{key: key, rule: rule, text: text}
  171. }
  172. } else {
  173. tarr = make([]*transText, 7, 7)
  174. t.rangeTanslations[key] = tarr
  175. }
  176. trans := &transText{
  177. text: text,
  178. indexes: make([]int, 4, 4),
  179. }
  180. tarr[rule] = trans
  181. idx := strings.Index(text, paramZero)
  182. if idx == -1 {
  183. tarr[rule] = nil
  184. return &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, are you sure you're adding a Range Translation?", paramZero)}
  185. }
  186. trans.indexes[0] = idx
  187. trans.indexes[1] = idx + len(paramZero)
  188. idx = strings.Index(text, paramOne)
  189. if idx == -1 {
  190. tarr[rule] = nil
  191. return &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, a Range Translation requires two parameters", paramOne)}
  192. }
  193. trans.indexes[2] = idx
  194. trans.indexes[3] = idx + len(paramOne)
  195. return nil
  196. }
  197. // T creates the translation for the locale given the 'key' and params passed in
  198. func (t *translator) T(key interface{}, params ...string) string {
  199. trans, ok := t.translations[key]
  200. if !ok {
  201. return unknownTranslation
  202. }
  203. b := make([]byte, 0, 64)
  204. var start, end, count int
  205. for i := 0; i < len(trans.indexes); i++ {
  206. end = trans.indexes[i]
  207. b = append(b, trans.text[start:end]...)
  208. b = append(b, params[count]...)
  209. i++
  210. start = trans.indexes[i]
  211. count++
  212. }
  213. b = append(b, trans.text[start:]...)
  214. return string(b)
  215. }
  216. // C creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in
  217. func (t *translator) C(key interface{}, num float64, digits uint64, param string) (string, error) {
  218. tarr, ok := t.cardinalTanslations[key]
  219. if !ok {
  220. return unknownTranslation, ErrUnknowTranslation
  221. }
  222. rule := t.CardinalPluralRule(num, digits)
  223. trans := tarr[rule]
  224. b := make([]byte, 0, 64)
  225. b = append(b, trans.text[:trans.indexes[0]]...)
  226. b = append(b, param...)
  227. b = append(b, trans.text[trans.indexes[1]:]...)
  228. return string(b), nil
  229. }
  230. // O creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in
  231. func (t *translator) O(key interface{}, num float64, digits uint64, param string) (string, error) {
  232. tarr, ok := t.ordinalTanslations[key]
  233. if !ok {
  234. return unknownTranslation, ErrUnknowTranslation
  235. }
  236. rule := t.OrdinalPluralRule(num, digits)
  237. trans := tarr[rule]
  238. b := make([]byte, 0, 64)
  239. b = append(b, trans.text[:trans.indexes[0]]...)
  240. b = append(b, param...)
  241. b = append(b, trans.text[trans.indexes[1]:]...)
  242. return string(b), nil
  243. }
  244. // R creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and 'digit2' arguments
  245. // and 'param1' and 'param2' passed in
  246. func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error) {
  247. tarr, ok := t.rangeTanslations[key]
  248. if !ok {
  249. return unknownTranslation, ErrUnknowTranslation
  250. }
  251. rule := t.RangePluralRule(num1, digits1, num2, digits2)
  252. trans := tarr[rule]
  253. b := make([]byte, 0, 64)
  254. b = append(b, trans.text[:trans.indexes[0]]...)
  255. b = append(b, param1...)
  256. b = append(b, trans.text[trans.indexes[1]:trans.indexes[2]]...)
  257. b = append(b, param2...)
  258. b = append(b, trans.text[trans.indexes[3]:]...)
  259. return string(b), nil
  260. }
  261. // VerifyTranslations checks to ensures that no plural rules have been
  262. // missed within the translations.
  263. func (t *translator) VerifyTranslations() error {
  264. for k, v := range t.cardinalTanslations {
  265. for _, rule := range t.PluralsCardinal() {
  266. if v[rule] == nil {
  267. return &ErrMissingPluralTranslation{translationType: "plural", rule: rule, key: k}
  268. }
  269. }
  270. }
  271. for k, v := range t.ordinalTanslations {
  272. for _, rule := range t.PluralsOrdinal() {
  273. if v[rule] == nil {
  274. return &ErrMissingPluralTranslation{translationType: "ordinal", rule: rule, key: k}
  275. }
  276. }
  277. }
  278. for k, v := range t.rangeTanslations {
  279. for _, rule := range t.PluralsRange() {
  280. if v[rule] == nil {
  281. return &ErrMissingPluralTranslation{translationType: "range", rule: rule, key: k}
  282. }
  283. }
  284. }
  285. return nil
  286. }