Passed
Pull Request — main (#22)
by Igor
01:48
created

scope.go   A

Size/Duplication

Total Lines 82
Duplicated Lines 0 %

Test Coverage

Coverage 95.65%

Importance

Changes 0
Metric Value
cc 12
eloc 45
dl 0
loc 82
ccs 22
cts 23
cp 0.9565
crap 12.0117
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A validation.Scope.withContext 0 4 1
A validation.*Scope.applyOptions 0 9 3
A validation.Scope.BuildViolation 0 11 3
A validation.Scope.atProperty 0 4 1
A validation.Scope.withLanguage 0 4 1
A validation.newScope 0 7 1
A validation.Scope.atIndex 0 4 1
A validation.Scope.Context 0 2 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