Passed
Push — main ( 66a50b...113ff1 )
by Rushan
59s queued 11s
created

validation.*Scope.applyOptions   A

Complexity

Conditions 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

Changes 0
Metric Value
cc 3
eloc 6
dl 0
loc 9
ccs 4
cts 5
cp 0.8
crap 3.072
rs 10
c 0
b 0
f 0
nop 1
1
package validation
2
3
import (
4
	"context"
5
6
	languagepkg "github.com/muonsoft/language"
7
	"golang.org/x/text/language"
8
)
9
10
// Scope holds the current state of validation. On the client-side of the package,
11
// it can be used to build violations.
12
type Scope struct {
13
	context          context.Context
14
	propertyPath     PropertyPath
15
	language         language.Tag
16
	translator       *Translator
17
	violationFactory ViolationFactory
18
}
19
20
// Context returns context value that was passed to the validator by Context argument or
21
// by creating scoped validator with the validator.WithContext method.
22
func (s Scope) Context() context.Context {
23 1
	return s.context
24
}
25
26
// BuildViolation is used to create violations in validation methods of constraints.
27
// This method automatically injects the property path and language of the current validation scope.
28
func (s Scope) BuildViolation(code, message string) *ViolationBuilder {
29 1
	b := NewViolationBuilder(s.violationFactory).BuildViolation(code, message)
30 1
	b.SetPropertyPath(s.propertyPath)
31
32 1
	if s.language != language.Und {
33 1
		b.SetLanguage(s.language)
34 1
	} else if s.context != nil {
35 1
		b.SetLanguage(languagepkg.FromContext(s.context))
36
	}
37
38 1
	return b
39
}
40
41
func (s *Scope) applyOptions(options ...Option) error {
42 1
	for _, option := range options {
43 1
		err := option.SetUp(s)
44 1
		if err != nil {
45
			return err
46
		}
47
	}
48
49 1
	return nil
50
}
51
52
func (s Scope) withContext(ctx context.Context) Scope {
53 1
	s.context = ctx
54
55 1
	return s
56
}
57
58
func (s Scope) withLanguage(tag language.Tag) Scope {
59 1
	s.language = tag
60
61 1
	return s
62
}
63
64
func (s Scope) atProperty(name string) Scope {
65 1
	s.propertyPath = append(s.propertyPath, PropertyNameElement(name))
66
67 1
	return s
68
}
69
70
func (s Scope) atIndex(index int) Scope {
71 1
	s.propertyPath = append(s.propertyPath, ArrayIndexElement(index))
72
73 1
	return s
74
}
75
76
func newScope() Scope {
77 1
	translator := newTranslator()
78
79 1
	return Scope{
80
		context:          context.Background(),
81
		translator:       translator,
82
		violationFactory: newViolationFactory(translator),
83
	}
84
}
85