Passed
Push — main ( 0f6dda...8fe6b9 )
by Igor
02:04 queued 11s
created

validation.ConditionalConstraint.validate   A

Complexity

Conditions 4

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

Changes 0
Metric Value
cc 4
eloc 15
nop 2
dl 0
loc 21
rs 9.65
c 0
b 0
f 0
ccs 9
cts 10
cp 0.9
crap 4.016
1
package validation
2
3
import (
4
	"github.com/muonsoft/validation/code"
5
	"github.com/muonsoft/validation/generic"
6
	"github.com/muonsoft/validation/message"
7
8
	"time"
9
)
10
11
// Constraint is the base interface to build validation constraints.
12
type Constraint interface {
13
	Option
14
	// Name is a constraint name that can be used in internal errors.
15
	Name() string
16
}
17
18
// NilConstraint is used for constraints that need to check value for nil. In common case
19
// you do not need to implement it in your constraints because nil values should be ignored.
20
type NilConstraint interface {
21
	Constraint
22
	ValidateNil(scope Scope) error
23
}
24
25
// BoolConstraint is used to build constraints for boolean values validation.
26
type BoolConstraint interface {
27
	Constraint
28
	ValidateBool(value *bool, scope Scope) error
29
}
30
31
// NumberConstraint is used to build constraints for numeric values validation.
32
//
33
// At this moment working with numbers is based on reflection.
34
// Be aware. This constraint is subject to be changed after generics implementation in Go.
35
type NumberConstraint interface {
36
	Constraint
37
	ValidateNumber(value generic.Number, scope Scope) error
38
}
39
40
// StringConstraint is used to build constraints for string values validation.
41
type StringConstraint interface {
42
	Constraint
43
	ValidateString(value *string, scope Scope) error
44
}
45
46
// IterableConstraint is used to build constraints for validation of iterables (arrays, slices, or maps).
47
//
48
// At this moment working with numbers is based on reflection.
49
// Be aware. This constraint is subject to be changed after generics implementation in Go.
50
type IterableConstraint interface {
51
	Constraint
52
	ValidateIterable(value generic.Iterable, scope Scope) error
53
}
54
55
// CountableConstraint is used to build constraints for simpler validation of iterable elements count.
56
type CountableConstraint interface {
57
	Constraint
58
	ValidateCountable(count int, scope Scope) error
59
}
60
61
// TimeConstraint is used to build constraints for date/time validation.
62
type TimeConstraint interface {
63
	Constraint
64
	ValidateTime(value *time.Time, scope Scope) error
65
}
66
67
type controlConstraint interface {
68
	validate(scope Scope, validate ValidateByConstraintFunc) (ViolationList, error)
69
}
70
71
// CustomStringConstraint can be used to create custom constraints for validating string values
72
// based on function with signature func(string) bool.
73
type CustomStringConstraint struct {
74
	isIgnored         bool
75
	isValid           func(string) bool
76
	name              string
77
	code              string
78
	messageTemplate   string
79
	messageParameters TemplateParameterList
80
}
81
82
// NewCustomStringConstraint creates a new string constraint from a function with signature func(string) bool.
83
// Optional parameters can be used to set up constraint name (first parameter), violation code (second),
84
// message template (third). All other parameters are ignored.
85
func NewCustomStringConstraint(isValid func(string) bool, parameters ...string) CustomStringConstraint {
86 1
	constraint := CustomStringConstraint{
87
		isValid:         isValid,
88
		name:            "CustomStringConstraint",
89
		code:            code.NotValid,
90
		messageTemplate: message.NotValid,
91
	}
92
93 1
	if len(parameters) > 0 {
94 1
		constraint.name = parameters[0]
95
	}
96 1
	if len(parameters) > 1 {
97 1
		constraint.code = parameters[1]
98
	}
99 1
	if len(parameters) > 2 {
100 1
		constraint.messageTemplate = parameters[2]
101
	}
102
103 1
	return constraint
104
}
105
106
// SetUp always returns no error.
107
func (c CustomStringConstraint) SetUp() error {
108 1
	return nil
109
}
110
111
// Name is the constraint name. It can be set via first parameter of function NewCustomStringConstraint.
112
func (c CustomStringConstraint) Name() string {
113 1
	return c.name
114
}
115
116
// Message sets the violation message template. You can set custom template parameters
117
// for injecting its values into the final message. Also, you can use default parameters:
118
//
119
//	{{ value }} - the current (invalid) value.
120
func (c CustomStringConstraint) Message(template string, parameters ...TemplateParameter) CustomStringConstraint {
121 1
	c.messageTemplate = template
122 1
	c.messageParameters = parameters
123 1
	return c
124
}
125
126
// When enables conditional validation of this constraint. If the expression evaluates to false,
127
// then the constraint will be ignored.
128
func (c CustomStringConstraint) When(condition bool) CustomStringConstraint {
129 1
	c.isIgnored = !condition
130 1
	return c
131
}
132
133
func (c CustomStringConstraint) ValidateString(value *string, scope Scope) error {
134 1
	if c.isIgnored || value == nil || *value == "" || c.isValid(*value) {
135 1
		return nil
136
	}
137
138 1
	return scope.BuildViolation(c.code, c.messageTemplate).
139
		SetParameters(
140
			c.messageParameters.Prepend(
141
				TemplateParameter{Key: "{{ value }}", Value: *value},
142
			)...,
143
		).
144
		AddParameter("{{ value }}", *value).
145
		CreateViolation()
146
}
147
148
// ConditionalConstraint is used for conditional validation.
149
// Use the When function to initiate a conditional check.
150
// If the condition is true, then the constraints passed through the Then function will be applied.
151
// Otherwise, the constraints passed through the Else function will apply.
152
type ConditionalConstraint struct {
153
	condition       bool
154
	thenConstraints []Constraint
155
	elseConstraints []Constraint
156
}
157
158
// When function is used to initiate conditional validation.
159
// If the condition is true, then the constraints passed through the Then function will be applied.
160
// Otherwise, the constraints passed through the Else function will apply.
161
func When(condition bool) ConditionalConstraint {
162 1
	return ConditionalConstraint{condition: condition}
163
}
164
165
// Then function is used to set a sequence of constraints to be applied if the condition is true.
166
// If the list is empty error will be returned.
167
func (c ConditionalConstraint) Then(constraints ...Constraint) ConditionalConstraint {
168 1
	c.thenConstraints = constraints
169 1
	return c
170
}
171
172
// Else function is used to set a sequence of constraints to be applied if a condition is false.
173
func (c ConditionalConstraint) Else(constraints ...Constraint) ConditionalConstraint {
174 1
	c.elseConstraints = constraints
175 1
	return c
176
}
177
178
// Name is the constraint name.
179
func (c ConditionalConstraint) Name() string {
180 1
	return "ConditionalConstraint"
181
}
182
183
// SetUp will return an error if Then function did not set any constraints.
184
func (c ConditionalConstraint) SetUp() error {
185 1
	if len(c.thenConstraints) == 0 {
186 1
		return errThenBranchNotSet
187
	}
188
189 1
	return nil
190
}
191
192
func (c ConditionalConstraint) validate(
193
	scope Scope,
194
	validate ValidateByConstraintFunc,
195
) (ViolationList, error) {
196 1
	violations := make(ViolationList, 0)
197 1
	var constraints []Constraint
198
199 1
	if c.condition {
200 1
		constraints = c.thenConstraints
201
	} else {
202 1
		constraints = c.elseConstraints
203
	}
204
205 1
	for _, constraint := range constraints {
206 1
		err := violations.AppendFromError(validate(constraint, scope))
207 1
		if err != nil {
208
			return nil, err
209
		}
210
	}
211
212 1
	return violations, nil
213
}
214
215
// SequentialConstraint is used to set constraints allowing to interrupt the validation once
216
// the first violation is raised.
217
type SequentialConstraint struct {
218
	constraints []Constraint
219
}
220
221
// Sequentially function used to set of constraints that should be validated step-by-step.
222
// If the list is empty error will be returned.
223
func Sequentially(constraints ...Constraint) SequentialConstraint {
224 1
	return SequentialConstraint{constraints: constraints}
225
}
226
227
// Name is the constraint name.
228
func (c SequentialConstraint) Name() string {
229 1
	return "SequentialConstraint"
230
}
231
232
// SetUp will return an error if the list of constraints is empty.
233
func (c SequentialConstraint) SetUp() error {
234 1
	if len(c.constraints) == 0 {
235 1
		return errSequentiallyConstraintsNotSet
236
	}
237 1
	return nil
238
}
239
240
func (c SequentialConstraint) validate(
241
	scope Scope,
242
	validate ValidateByConstraintFunc,
243
) (ViolationList, error) {
244 1
	violations := make(ViolationList, 0)
245
246 1
	for _, constraint := range c.constraints {
247 1
		err := violations.AppendFromError(validate(constraint, scope))
248 1
		if err != nil {
249
			return nil, err
250 1
		} else if len(violations) > 0 {
251 1
			return violations, nil
252
		}
253
	}
254
255
	return violations, nil
256
}
257
258
type notFoundConstraint struct {
259
	key string
260
}
261
262
func (c notFoundConstraint) SetUp() error {
263 1
	return ConstraintNotFoundError{Key: c.key}
264
}
265
266
func (c notFoundConstraint) Name() string {
267 1
	return "notFoundConstraint"
268
}
269