|
| 1 | +// Copyright (c) HashiCorp, Inc. |
| 2 | +// SPDX-License-Identifier: MPL-2.0 |
| 3 | + |
| 4 | +package dynamicvalidator |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "fmt" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/hashicorp/terraform-plugin-framework/schema/validator" |
| 12 | +) |
| 13 | + |
| 14 | +// All returns a validator which ensures that any configured attribute value |
| 15 | +// attribute value validates against all the given validators. |
| 16 | +// |
| 17 | +// Use of All is only necessary when used in conjunction with Any or AnyWithAllWarnings |
| 18 | +// as the Validators field automatically applies a logical AND. |
| 19 | +func All(validators ...validator.Dynamic) validator.Dynamic { |
| 20 | + return allValidator{ |
| 21 | + validators: validators, |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +var _ validator.Dynamic = allValidator{} |
| 26 | + |
| 27 | +// allValidator implements the validator. |
| 28 | +type allValidator struct { |
| 29 | + validators []validator.Dynamic |
| 30 | +} |
| 31 | + |
| 32 | +// Description describes the validation in plain text formatting. |
| 33 | +func (v allValidator) Description(ctx context.Context) string { |
| 34 | + var descriptions []string |
| 35 | + |
| 36 | + for _, subValidator := range v.validators { |
| 37 | + descriptions = append(descriptions, subValidator.Description(ctx)) |
| 38 | + } |
| 39 | + |
| 40 | + return fmt.Sprintf("Value must satisfy all of the validations: %s", strings.Join(descriptions, " + ")) |
| 41 | +} |
| 42 | + |
| 43 | +// MarkdownDescription describes the validation in Markdown formatting. |
| 44 | +func (v allValidator) MarkdownDescription(ctx context.Context) string { |
| 45 | + return v.Description(ctx) |
| 46 | +} |
| 47 | + |
| 48 | +// ValidateDynamic performs the validation. |
| 49 | +func (v allValidator) ValidateDynamic(ctx context.Context, req validator.DynamicRequest, resp *validator.DynamicResponse) { |
| 50 | + for _, subValidator := range v.validators { |
| 51 | + validateResp := &validator.DynamicResponse{} |
| 52 | + |
| 53 | + subValidator.ValidateDynamic(ctx, req, validateResp) |
| 54 | + |
| 55 | + resp.Diagnostics.Append(validateResp.Diagnostics...) |
| 56 | + } |
| 57 | +} |
0 commit comments