Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions internal/helper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,20 @@ func (h *Helper) ErrorT(ctx context.Context, field fmap.Field, value any, locale
}
}

// paramsTranslator is a translator that passes the named parameters to its sources, the translator of valigo is.
type paramsTranslator interface {
TParams(ctx context.Context, key string, args []any, params map[string]any) string
}

// ErrorParams is ErrorT with the named parameters of the message for the sources of the translator.
func (h *Helper) ErrorParams(ctx context.Context, field fmap.Field, value any, localeKey string, args []any, params map[string]any) shared.Error {
pt, ok := h.Translator.(paramsTranslator)
if !ok {
return h.ErrorT(ctx, field, value, localeKey, args...)
}
return shared.Error{Location: h.Location(field), Message: pt.TParams(ctx, localeKey, args, params), Value: value, Code: localeKey}
}

// FieldLocation returns the location of the field in errors.
func (h *Helper) FieldLocation(field fmap.Field) string {
return h.Location(field)
Expand Down
20 changes: 20 additions & 0 deletions internal/helper/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,23 @@ func TestHelperFieldLocation(t *testing.T) {
t.Errorf("FieldLocation() = %q, want Name", got)
}
}

// plainTranslator is a translator without the named parameters.
type plainTranslator struct{}

func (plainTranslator) ErrorT(_ context.Context, format string, _ ...any) error { return nil }
func (plainTranslator) T(_ context.Context, format string, _ ...any) string { return "plain " + format }

func TestHelperErrorParams(t *testing.T) {
strg, _ := fmap.GetFrom(admin{})
field := strg.MustFind("Name")
h := New()
err := h.ErrorParams(context.Background(), field, "v", "validation:string:Cannot be longer than %d characters", []any{3}, map[string]any{"max": 3})
if err.Message != "Cannot be longer than 3 characters" || err.Location != "Name" || err.Code != "validation:string:Cannot be longer than %d characters" {
t.Errorf("ErrorParams: %+v", err)
}
h.Translator = plainTranslator{}
if err := h.ErrorParams(context.Background(), field, "v", "k", nil, nil); err.Message != "plain k" {
t.Errorf("ErrorParams of a translator without the parameters: %+v", err)
}
}
13 changes: 12 additions & 1 deletion shared/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,23 @@ func (m Msg) with(name string, value any) Msg {
}

// Error builds the error of the field with the translated message, the code and the parameters of m.
// The helper of the validator passes the named parameters to the translator, for the sources with named placeholders.
func (m Msg) Error(ctx context.Context, h Helper, field fmap.Field, value any) Error {
err := h.ErrorT(ctx, field, value, m.Key, m.Args...)
var err Error
if ph, ok := h.(paramsHelper); ok {
err = ph.ErrorParams(ctx, field, value, m.Key, m.Args, m.Params)
} else {
err = h.ErrorT(ctx, field, value, m.Key, m.Args...)
}
err.Code, err.Params = m.Code, m.Params
return err
}

// paramsHelper is a Helper that passes the named parameters of the messages to the translator.
type paramsHelper interface {
ErrorParams(ctx context.Context, field fmap.Field, value any, key string, args []any, params map[string]any) Error
}

// key returns the message of a rule configured by a locale key, its code is the key.
func key(localeKey string, args []any) Msg {
return Msg{Code: localeKey, Key: localeKey, Args: args}
Expand Down
15 changes: 15 additions & 0 deletions shared/message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ package shared

import (
"context"
"fmt"
"testing"

"github.com/insei/fmap/v3"

"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -117,3 +120,15 @@ func TestMapMessages(t *testing.T) {
newLabels(&required).Required()
assert.Equal(t, []Error{{Location: "Labels", Message: "validation:map:Should be fulfilled", Code: "map.required"}}, required.validateFull(&mapsSample{}))
}

// paramsPathHelper is pathHelper that builds the messages of the named parameters.
type paramsPathHelper struct{ pathHelper }

func (paramsPathHelper) ErrorParams(_ context.Context, field fmap.Field, value any, key string, _ []any, params map[string]any) Error {
return Error{Location: field.GetStructPath(), Message: fmt.Sprint(key, params), Value: value}
}

func TestMsgErrorParams(t *testing.T) {
err := M("string.max_len", "max", P("max", 3)).Error(context.Background(), paramsPathHelper{}, sampleField(t, "Text"), "abcd")
assert.Equal(t, Error{Location: "Text", Message: "maxmap[max:3]", Value: "abcd", Code: "string.max_len", Params: map[string]any{"max": 3}}, err)
}
28 changes: 18 additions & 10 deletions translator/inmem.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package translator

import (
"fmt"
"io/fs"
"strings"
)
Expand Down Expand Up @@ -85,18 +84,27 @@ func (t *inMemTranslatorStorage) Merge(locales map[string]map[string]string) {
// Get returns the translated value for a given format and language preferences.
// A format with plural forms (format#one, format#few, format#many, format#other) is translated
// by the plural category of the first integer argument in the language.
func (t *inMemTranslatorStorage) Get(prefer []string, format string, args ...any) string {
translatedFormat := format
for _, preferLang := range prefer {
if langFormat, ok := t.translate(preferLang, format, args); ok {
translatedFormat = langFormat
break
func (t *inMemTranslatorStorage) Get(prefer []string, key string, args ...any) string {
return t.getParams(prefer, key, args, nil)
}

// getParams is Get, the storage has no named placeholders.
func (t *inMemTranslatorStorage) getParams(prefer []string, key string, args []any, _ map[string]any) string {
for _, lang := range prefer {
if msg, ok := t.Translate(lang, key, args, nil); ok {
return msg
}
}
if len(args) == 0 && strings.IndexByte(translatedFormat, '%') < 0 {
return translatedFormat
return format(key, args)
}

// Translate returns the translation of the key in the language, see Source.
func (t *inMemTranslatorStorage) Translate(lang, key string, args []any, _ map[string]any) (string, bool) {
langFormat, ok := t.translate(lang, key, args)
if !ok {
return "", false
}
return fmt.Sprintf(translatedFormat, args...)
return format(langFormat, args), true
}

// translate returns the translation of format in lang, the plural form if the format has plural forms.
Expand Down
65 changes: 65 additions & 0 deletions translator/source.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package translator

import (
"fmt"
"strings"
)

// Source is a source of the translations of the messages: the YAML locales of valigo, a bundle of go-i18n...
// A translator looks the languages of a request up in its sources in order, see WithSources.
type Source interface {
// Translate returns the message of the key in the language formatted with the arguments, false if the source
// has no translation of the key in the language. args are the format arguments of the key, params are the same
// values by their names, e.g. {"max": 64}, for the sources with named placeholders; params can be nil.
Translate(lang, key string, args []any, params map[string]any) (string, bool)
}

// WithSources returns an option that looks the translations up in the sources: for every language of a request
// in order, the first source with a translation of the key wins. Your messages go before the built-in ones,
// the built-in ones translate the rest:
//
// translator.New(translator.WithSources(goi18n.Source(bundle), translator.Embedded()))
//
// A key without a translation in any language is the message itself.
func WithSources(sources ...Source) Option {
return &storageOption{storage: &sourcesStorage{sources: sources}}
}

// Embedded returns the source of the built-in YAML locales of valigo, the options add your translations to them.
func Embedded(opts ...InMemStorageOption) Source {
return newInMemStorage(EmbedFSLocalesYAML, opts...).(*inMemTranslatorStorage)
}

// paramsStorage is a storage that passes the named parameters of the messages to its sources.
type paramsStorage interface {
getParams(prefer []string, key string, args []any, params map[string]any) string
}

// sourcesStorage is the storage of the translations of the sources, see WithSources.
type sourcesStorage struct {
sources []Source
}

// Get returns the translation of the key in the first of the preferred languages that has one.
func (s *sourcesStorage) Get(prefer []string, key string, args ...any) string {
return s.getParams(prefer, key, args, nil)
}

func (s *sourcesStorage) getParams(prefer []string, key string, args []any, params map[string]any) string {
for _, lang := range prefer {
for _, source := range s.sources {
if msg, ok := source.Translate(lang, key, args, params); ok {
return msg
}
}
}
return format(key, args)
}

// format formats the message with the arguments, a message without arguments and verbs is returned as is.
func format(msg string, args []any) string {
if len(args) == 0 && strings.IndexByte(msg, '%') < 0 {
return msg
}
return fmt.Sprintf(msg, args...)
}
57 changes: 57 additions & 0 deletions translator/source_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package translator

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
)

// mapSource translates the keys of its languages and keeps the parameters of the last translation.
type mapSource struct {
messages map[string]map[string]string
params map[string]any
}

func (s *mapSource) Translate(lang, key string, args []any, params map[string]any) (string, bool) {
msg, ok := s.messages[lang][key]
if ok {
s.params = params
}
return format(msg, args), ok
}

func TestWithSources(t *testing.T) {
own := &mapSource{messages: map[string]map[string]string{
"ru": {"validation:string:Should be email address": "Нужен e-mail"},
"en": {"validation:string:Should be URL": "A link, please", "greeting %s": "Hello, %s"},
}}
tr := New(WithSources(own, Embedded()))
ru := ContextWithLanguages(context.Background(), "ru")
assert.Equal(t, "Нужен e-mail", tr.T(ru, "validation:string:Should be email address"), "the first source")
assert.Equal(t, "Должно быть URL", tr.T(ru, "validation:string:Should be URL"),
"the built-in source of the language before the first source of the default language")
assert.Equal(t, "Hello, Ann", tr.T(context.Background(), "greeting %s", "Ann"))
assert.Equal(t, "no translation 1", tr.T(ru, "no translation %d", 1), "the key itself")
assert.Equal(t, "plain", tr.T(ru, "plain"))
assert.EqualError(t, tr.ErrorT(ru, "validation:string:Should be email address"), "Нужен e-mail")

pt := tr.(*translator)
params := map[string]any{"max": 3}
assert.Equal(t, "Нужен e-mail", pt.TParams(ru, "validation:string:Should be email address", nil, params))
assert.Equal(t, params, own.params, "the parameters reach the source")
}

// plainStorage is a storage without the parameters.
type plainStorage struct{}

func (plainStorage) Get(_ []string, key string, _ ...any) string { return "plain " + key }

func TestTParamsOfStorages(t *testing.T) {
assert.Equal(t, "plain k", New(WithStorage(plainStorage{})).(*translator).TParams(context.Background(), "k", nil, nil))
builtin := New().(*translator)
assert.Equal(t, "Should be URL", builtin.TParams(context.Background(), "validation:string:Should be URL", nil, map[string]any{"x": 1}))
assert.Equal(t, "Should be URL", NewInMemStorage().Get([]string{"en"}, "validation:string:Should be URL"))
_, ok := Embedded().Translate("xx", "validation:string:Should be URL", nil, nil)
assert.False(t, ok)
}
8 changes: 8 additions & 0 deletions translator/translator.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ func (t *translator) T(ctx context.Context, format string, args ...any) string {
return t.storage.Get(t.getLanguages(ctx), format, args...)
}

// TParams returns the translated message, the named parameters are passed to the sources, see Source.
func (t *translator) TParams(ctx context.Context, key string, args []any, params map[string]any) string {
if s, ok := t.storage.(paramsStorage); ok {
return s.getParams(t.getLanguages(ctx), key, args, params)
}
return t.storage.Get(t.getLanguages(ctx), key, args...)
}

// New returns a new Translator instance with default settings.
func New(opts ...Option) Translator {
t := &translator{
Expand Down
Loading