diff --git a/pkg/schema/schema.go b/pkg/schema/schema.go index 4fec4c174684745be718abf4c2a595f7fe1ae3fe..28fad2579f19de250304d6ff74d07c1245066697 100644 --- a/pkg/schema/schema.go +++ b/pkg/schema/schema.go @@ -5,7 +5,9 @@ import ( "io/fs" "path/filepath" "reflect" + "strings" + "git.perx.ru/perxis/perxis-go/pkg/data" "git.perx.ru/perxis/perxis-go/pkg/errors" "git.perx.ru/perxis/perxis-go/pkg/expr" "git.perx.ru/perxis/perxis-go/pkg/schema/field" @@ -290,3 +292,35 @@ func (s *Schema) Introspect(ctx context.Context, data map[string]interface{}) (m return val, mutatedSchema, nil } + +func (s *Schema) IsFieldSingleLocale(path string) bool { + if s.SingleLocale { + return true + } + subpaths := getSubpaths(path) + fields := s.GetFields(func(_ *field.Field, p string) bool { return data.Contains(p, subpaths) }) + if len(fields) != len(subpaths) { + return false // Поле не найдено + } + for _, f := range fields { + if f.SingleLocale { + return true + } + if f.Path == path { + return f.SingleLocale + } + } + return false +} + +func getSubpaths(path string) (res []string) { + var cur string + for _, p := range strings.Split(path, field.FieldSeparator) { + if cur != "" { + cur += field.FieldSeparator + } + cur += p + res = append(res, cur) + } + return res +} diff --git a/pkg/schema/schema_test.go b/pkg/schema/schema_test.go new file mode 100644 index 0000000000000000000000000000000000000000..462f3b8fff06d58c43a94ef0881f24ec46f68437 --- /dev/null +++ b/pkg/schema/schema_test.go @@ -0,0 +1,42 @@ +package schema + +import ( + "testing" + + "git.perx.ru/perxis/perxis-go/pkg/schema/field" +) + +func TestSchema_IsFieldSingleLocale(t *testing.T) { + tests := []struct { + name string + path string + want bool + }{ + {"string field on first level", "b", true}, + {"string field on first level", "d", false}, + {"string nested field", "a.a", false}, + {"string nested field", "a.b", true}, + {"string field inside SingleLocale object", "c.a", true}, + {"string field inside SingleLocale object", "c.b", true}, + {"object", "c", true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := New( + "a", field.Object( + "a", field.String(), + "b", field.String().SetSingleLocale(true), + ), + "b", field.String().SetSingleLocale(true), + "c", field.Object( + "a", field.String(), + "b", field.String(), + ).SetSingleLocale(true), + "d", field.String(), + ) + if got := s.IsFieldSingleLocale(tt.path); got != tt.want { + t.Errorf("IsFieldSingleLocale() = %v, want %v", got, tt.want) + } + }) + } +}