Skip to content

Commit

Permalink
Merge pull request #73 from muonsoft/next
Browse files Browse the repository at this point in the history
violation list builder
  • Loading branch information
strider2038 authored Apr 21, 2022
2 parents aafecfa + 6e37e0f commit b26c626
Show file tree
Hide file tree
Showing 23 changed files with 479 additions and 134 deletions.
4 changes: 2 additions & 2 deletions arguments.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,8 +345,8 @@ func (c Checker) validate(scope Scope) (*ViolationList, error) {
}

violation := scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(c.messageParameters...).
CreateViolation()
WithParameters(c.messageParameters...).
Create()

return NewViolationList(violation), nil
}
6 changes: 3 additions & 3 deletions contraint.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,11 @@ func (c CustomStringConstraint) ValidateString(value *string, scope Scope) error
}

return scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(
WithParameters(
c.messageParameters.Prepend(
TemplateParameter{Key: "{{ value }}", Value: *value},
)...,
).
AddParameter("{{ value }}", *value).
CreateViolation()
WithParameter("{{ value }}", *value).
Create()
}
4 changes: 1 addition & 3 deletions example_context_with_recursion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ func (c NestingLimitConstraint) ValidateProperty(property *Property, scope valid
}

if level >= c.limit {
return scope.
BuildViolation("nestingLimitReached", "Maximum nesting level reached.").
CreateViolation()
return scope.CreateViolation("nestingLimitReached", "Maximum nesting level reached.")
}

return nil
Expand Down
4 changes: 2 additions & 2 deletions example_custom_argument_constraint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ func (c *UniqueBrandConstraint) ValidateBrand(brand *Brand, scope validation.Sco
return scope.
BuildViolation("notUniqueBrand", `Brand with name "{{ name }}" already exists.`).
// you can inject parameter value to the message here
AddParameter("{{ name }}", brand.Name).
CreateViolation()
WithParameter("{{ name }}", brand.Name).
Create()
}

func ExampleNewArgument_customArgumentConstraintValidator() {
Expand Down
2 changes: 1 addition & 1 deletion example_custom_constraint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (c NumericConstraint) ValidateString(value *string, scope validation.Scope)
}

// use the scope to build violation with translations
return scope.BuildViolation("notNumeric", "This value should be numeric.").CreateViolation()
return scope.CreateViolation("notNumeric", "This value should be numeric.")
}

func ExampleValidator_Validate_customConstraint() {
Expand Down
4 changes: 2 additions & 2 deletions example_custom_service_constraint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ func (c *ExistingTagConstraint) ValidateString(value *string, scope validation.S
return scope.
BuildViolation("unknownTag", `Tag "{{ value }}" does not exist.`).
// you can inject parameter value to the message here
AddParameter("{{ value }}", *value).
CreateViolation()
WithParameter("{{ value }}", *value).
Create()
}

type StockItem struct {
Expand Down
63 changes: 54 additions & 9 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1034,15 +1034,34 @@ func ExampleValidator_Validate_translationForCustomMessage() {
// violation: теги должны содержать 1 элемент и более
}

func ExampleValidator_CreateViolation() {
validator, err := validation.NewValidator()
if err != nil {
log.Fatal(err)
}

violation := validator.CreateViolation(
context.Background(),
"clientCode",
"Client message.",
validation.PropertyNameElement("properties"),
validation.ArrayIndexElement(1),
)

fmt.Println(violation.Error())
// Output:
// violation at 'properties[1]': Client message.
}

func ExampleValidator_BuildViolation_buildingViolation() {
validator, err := validation.NewValidator()
if err != nil {
log.Fatal(err)
}

violation := validator.BuildViolation(context.Background(), "clientCode", "Client message with {{ parameter }}.").
AddParameter("{{ parameter }}", "value").
CreateViolation()
WithParameter("{{ parameter }}", "value").
Create()

fmt.Println(violation.Message())
// Output:
Expand All @@ -1064,22 +1083,48 @@ func ExampleValidator_BuildViolation_translatableParameter() {

violation := validator.WithLanguage(language.Russian).
BuildViolation(context.Background(), "clientCode", "The operation is only possible for the {{ role }}.").
SetParameters(validation.TemplateParameter{
WithParameters(validation.TemplateParameter{
Key: "{{ role }}",
Value: "administrator role",
NeedsTranslation: true,
}).
CreateViolation()
Create()

fmt.Println(violation.Message())
// Output:
// Операция возможна только для роли администратора.
}

func ExampleValidator_BuildViolationList() {
validator, err := validation.NewValidator()
if err != nil {
log.Fatal(err)
}

builder := validator.BuildViolationList(context.Background())
builder.BuildViolation("code1", "Client message with {{ parameter 1 }}.").
WithParameter("{{ parameter 1 }}", "value 1").
AtProperty("properties").AtIndex(0).
Add()
builder.BuildViolation("code2", "Client message with {{ parameter 2 }}.").
WithParameter("{{ parameter 2 }}", "value 2").
AtProperty("properties").AtIndex(1).
Add()
violations := builder.Create()

violations.Each(func(i int, violation validation.Violation) error {
fmt.Println(violation.Error())
return nil
})
// Output:
// violation at 'properties[0]': Client message with value 1.
// violation at 'properties[1]': Client message with value 2.
}

func ExampleViolationList_First() {
violations := validation.NewViolationList(
validator.BuildViolation(context.Background(), "", "foo").CreateViolation(),
validator.BuildViolation(context.Background(), "", "bar").CreateViolation(),
validator.BuildViolation(context.Background(), "", "foo").Create(),
validator.BuildViolation(context.Background(), "", "bar").Create(),
)

for violation := violations.First(); violation != nil; violation = violation.Next() {
Expand All @@ -1092,7 +1137,7 @@ func ExampleViolationList_First() {

func ExampleViolationList_AppendFromError_addingViolation() {
violations := validation.NewViolationList()
err := validator.BuildViolation(context.Background(), "", "foo").CreateViolation()
err := validator.BuildViolation(context.Background(), "", "foo").Create()

appendErr := violations.AppendFromError(err)

Expand All @@ -1106,8 +1151,8 @@ func ExampleViolationList_AppendFromError_addingViolation() {
func ExampleViolationList_AppendFromError_addingViolationList() {
violations := validation.NewViolationList()
err := validation.NewViolationList(
validator.BuildViolation(context.Background(), "", "foo").CreateViolation(),
validator.BuildViolation(context.Background(), "", "bar").CreateViolation(),
validator.BuildViolation(context.Background(), "", "foo").Create(),
validator.BuildViolation(context.Background(), "", "bar").Create(),
)

appendErr := violations.AppendFromError(err)
Expand Down
12 changes: 6 additions & 6 deletions flow_control.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ func (arg WhenArgument) setUp(ctx *executionContext) {
ctx.addValidator(arg.options, func(scope Scope) (*ViolationList, error) {
var err error
if arg.isTrue {
err = scope.validate(arg.thenArguments...)
err = scope.Validate(arg.thenArguments...)
} else {
err = scope.validate(arg.elseArguments...)
err = scope.Validate(arg.elseArguments...)
}

return unwrapViolationList(err)
Expand Down Expand Up @@ -88,9 +88,9 @@ func (arg WhenGroupsArgument) setUp(ctx *executionContext) {
ctx.addValidator(arg.options, func(scope Scope) (*ViolationList, error) {
var err error
if scope.IsIgnored(arg.groups...) {
err = scope.validate(arg.elseArguments...)
err = scope.Validate(arg.elseArguments...)
} else {
err = scope.validate(arg.thenArguments...)
err = scope.Validate(arg.thenArguments...)
}

return unwrapViolationList(err)
Expand Down Expand Up @@ -131,7 +131,7 @@ func (arg SequentialArgument) setUp(ctx *executionContext) {
violations := &ViolationList{}

for _, argument := range arg.arguments {
err := violations.AppendFromError(scope.validate(argument))
err := violations.AppendFromError(scope.Validate(argument))
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -180,7 +180,7 @@ func (arg AtLeastOneOfArgument) setUp(ctx *executionContext) {
violations := &ViolationList{}

for _, argument := range arg.arguments {
violation := scope.validate(argument)
violation := scope.Validate(argument)
if violation == nil {
return nil, nil
}
Expand Down
20 changes: 10 additions & 10 deletions it/basic.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,8 @@ func (c NotBlankConstraint[T]) ValidateTime(value *time.Time, scope validation.S

func (c NotBlankConstraint[T]) newViolation(scope validation.Scope) validation.Violation {
return scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(c.messageParameters...).
CreateViolation()
WithParameters(c.messageParameters...).
Create()
}

// BlankConstraint checks that a value is blank: equal to false, nil, zero, an empty string, an empty
Expand Down Expand Up @@ -249,8 +249,8 @@ func (c BlankConstraint[T]) ValidateTime(value *time.Time, scope validation.Scop

func (c BlankConstraint[T]) newViolation(scope validation.Scope) validation.Violation {
return scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(c.messageParameters...).
CreateViolation()
WithParameters(c.messageParameters...).
Create()
}

// NotNilConstraint checks that a value in not strictly equal to nil. To check that values in not blank use
Expand Down Expand Up @@ -338,8 +338,8 @@ func (c NotNilConstraint[T]) ValidateTime(value *time.Time, scope validation.Sco

func (c NotNilConstraint[T]) newViolation(scope validation.Scope) validation.Violation {
return scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(c.messageParameters...).
CreateViolation()
WithParameters(c.messageParameters...).
Create()
}

// NilConstraint checks that a value in strictly equal to nil. To check that values in blank use
Expand Down Expand Up @@ -427,8 +427,8 @@ func (c NilConstraint[T]) ValidateTime(value *time.Time, scope validation.Scope)

func (c NilConstraint[T]) newViolation(scope validation.Scope) validation.Violation {
return scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(c.messageParameters...).
CreateViolation()
WithParameters(c.messageParameters...).
Create()
}

// BoolConstraint checks that a bool value in strictly equal to expected bool value.
Expand Down Expand Up @@ -492,6 +492,6 @@ func (c BoolConstraint) ValidateBool(value *bool, scope validation.Scope) error
}

return scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(c.messageParameters...).
CreateViolation()
WithParameters(c.messageParameters...).
Create()
}
4 changes: 2 additions & 2 deletions it/choice.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,11 @@ func (c ChoiceConstraint[T]) ValidateComparable(value *T, scope validation.Scope

return scope.
BuildViolation(c.code, c.messageTemplate).
SetParameters(
WithParameters(
c.messageParameters.Prepend(
validation.TemplateParameter{Key: "{{ value }}", Value: fmt.Sprint(*value)},
validation.TemplateParameter{Key: "{{ choices }}", Value: c.choicesValue},
)...,
).
CreateViolation()
Create()
}
24 changes: 12 additions & 12 deletions it/comparison.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,13 @@ func (c ComparisonConstraint[T]) ValidateComparable(value *T, scope validation.S
}

return scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(
WithParameters(
c.messageParameters.Prepend(
validation.TemplateParameter{Key: "{{ comparedValue }}", Value: c.comparedValue},
validation.TemplateParameter{Key: "{{ value }}", Value: formatComparable(*value)},
)...,
).
CreateViolation()
Create()
}

// NumberComparisonConstraint is used for various numeric comparisons between integer and float values.
Expand Down Expand Up @@ -280,13 +280,13 @@ func (c NumberComparisonConstraint[T]) ValidateNumber(value *T, scope validation
}

return scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(
WithParameters(
c.messageParameters.Prepend(
validation.TemplateParameter{Key: "{{ comparedValue }}", Value: c.comparedValue},
validation.TemplateParameter{Key: "{{ value }}", Value: fmt.Sprint(*value)},
)...,
).
CreateViolation()
Create()
}

// RangeConstraint is used to check that a given number value is between some minimum and maximum.
Expand Down Expand Up @@ -362,14 +362,14 @@ func (c RangeConstraint[T]) ValidateNumber(value *T, scope validation.Scope) err

func (c RangeConstraint[T]) newViolation(value T, scope validation.Scope) error {
return scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(
WithParameters(
c.messageParameters.Prepend(
validation.TemplateParameter{Key: "{{ min }}", Value: fmt.Sprint(c.min)},
validation.TemplateParameter{Key: "{{ max }}", Value: fmt.Sprint(c.max)},
validation.TemplateParameter{Key: "{{ value }}", Value: fmt.Sprint(value)},
)...,
).
CreateViolation()
Create()
}

// TimeComparisonConstraint is used to compare time values.
Expand Down Expand Up @@ -484,13 +484,13 @@ func (c TimeComparisonConstraint) ValidateTime(value *time.Time, scope validatio
}

return scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(
WithParameters(
c.messageParameters.Prepend(
validation.TemplateParameter{Key: "{{ comparedValue }}", Value: c.comparedValue.Format(c.layout)},
validation.TemplateParameter{Key: "{{ value }}", Value: value.Format(c.layout)},
)...,
).
CreateViolation()
Create()
}

// TimeRangeConstraint is used to check that a given time value is between some minimum and maximum.
Expand Down Expand Up @@ -572,14 +572,14 @@ func (c TimeRangeConstraint) ValidateTime(value *time.Time, scope validation.Sco

func (c TimeRangeConstraint) newViolation(value *time.Time, scope validation.Scope) validation.Violation {
return scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(
WithParameters(
c.messageParameters.Prepend(
validation.TemplateParameter{Key: "{{ min }}", Value: c.min.Format(c.layout)},
validation.TemplateParameter{Key: "{{ max }}", Value: c.max.Format(c.layout)},
validation.TemplateParameter{Key: "{{ value }}", Value: value.Format(c.layout)},
)...,
).
CreateViolation()
Create()
}

// UniqueConstraint is used to check that all elements of the given collection are unique.
Expand Down Expand Up @@ -633,8 +633,8 @@ func (c UniqueConstraint[T]) ValidateComparables(values []T, scope validation.Sc
}

return scope.BuildViolation(c.code, c.messageTemplate).
SetParameters(c.messageParameters...).
CreateViolation()
WithParameters(c.messageParameters...).
Create()
}

func formatComparable[T comparable](value T) string {
Expand Down
6 changes: 3 additions & 3 deletions it/iterable.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,12 @@ func (c CountConstraint) newViolation(
}

return scope.BuildViolation(violationCode, template).
SetPluralCount(limit).
SetParameters(
WithPluralCount(limit).
WithParameters(
parameters.Prepend(
validation.TemplateParameter{Key: "{{ count }}", Value: strconv.Itoa(count)},
validation.TemplateParameter{Key: "{{ limit }}", Value: strconv.Itoa(limit)},
)...,
).
CreateViolation()
Create()
}
Loading

0 comments on commit b26c626

Please sign in to comment.