Passed
Pull Request — main (#23)
by Igor
01:32
created

it.ChoiceConstraint.Message   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
nop 1
1
package it
2
3
import (
4
	"strings"
5
6
	"github.com/muonsoft/validation"
7
	"github.com/muonsoft/validation/code"
8
	"github.com/muonsoft/validation/message"
9
)
10
11
// ChoiceConstraint is used to ensure that the given value corresponds to one of the expected choices.
12
type ChoiceConstraint struct {
13
	choices         map[string]bool
14
	choicesValue    string
15
	messageTemplate string
16
	isIgnored       bool
17
}
18
19
// IsOneOfStrings creates a ChoiceConstraint for checking that values are in the expected list of strings.
20
//
21
// Example
22
//	err := validator.ValidateString(&s, it.IsOneOfStrings("one", "two", "three"))
23
func IsOneOfStrings(values ...string) ChoiceConstraint {
24 1
	choices := make(map[string]bool, len(values))
25 1
	for _, value := range values {
26 1
		choices[value] = true
27
	}
28
29 1
	return ChoiceConstraint{
30
		choices:         choices,
31
		choicesValue:    strings.Join(values, ", "),
32
		messageTemplate: message.NoSuchChoice,
33
	}
34
}
35
36
// SetUp will return an error if the list of choices is empty.
37
func (c ChoiceConstraint) SetUp(scope *validation.Scope) error {
38 1
	if len(c.choices) == 0 {
39 1
		return errEmptyChoices
40
	}
41
42 1
	return nil
43
}
44
45
// Name is the constraint name.
46
func (c ChoiceConstraint) Name() string {
47 1
	return "ChoiceConstraint"
48
}
49
50
// Message sets the violation message template. You can use template parameters
51
// for injecting its values into the final message:
52
//
53
//	{{ choices }} - a comma-separated list of available choices;
54
//	{{ value }} - the current (invalid) value.
55
func (c ChoiceConstraint) Message(message string) ChoiceConstraint {
56 1
	c.messageTemplate = message
57 1
	return c
58
}
59
60
// When enables conditional validation of this constraint. If the expression evaluates to false,
61
// then the constraint will be ignored.
62
func (c ChoiceConstraint) When(condition bool) ChoiceConstraint {
63 1
	c.isIgnored = !condition
64 1
	return c
65
}
66
67
func (c ChoiceConstraint) ValidateString(value *string, scope validation.Scope) error {
68 1
	if c.isIgnored || value == nil || *value == "" {
69 1
		return nil
70
	}
71 1
	if c.choices[*value] {
72 1
		return nil
73
	}
74
75 1
	return scope.
76
		BuildViolation(code.NoSuchChoice, c.messageTemplate).
77
		SetParameters(map[string]string{
78
			"{{ value }}":   *value,
79
			"{{ choices }}": c.choicesValue,
80
		}).
81
		GetViolation()
82
}
83