github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/inputvalidation/validators_map.go (about) 1 /* 2 Part of this file is copied from https://github.com/go-ozzo/ozzo-validation/blob/master/each.go. 3 Below you can find its licence. 4 5 The MIT License (MIT) 6 Copyright (c) 2016, Qiang Xue 7 8 Permission is hereby granted, free of charge, to any person obtaining a copy of this software 9 and associated documentation files (the "Software"), to deal in the Software without restriction, 10 including without limitation the rights to use, copy, modify, merge, publish, distribute, 11 sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 12 is furnished to do so, subject to the following conditions: 13 14 The above copyright notice and this permission notice shall be included in all copies or 15 substantial portions of the Software. 16 17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 18 BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 20 DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 */ 23 24 package inputvalidation 25 26 import ( 27 "errors" 28 "reflect" 29 30 validation "github.com/go-ozzo/ozzo-validation/v4" 31 ) 32 33 type eachKeyRule []validation.Rule 34 35 // EachKey returns a validation rule that loops through a map and validates each key inside with the provided rules. 36 // An empty iterable is considered valid. Use the Required rule to make sure the iterable is not empty. 37 func EachKey(rules ...validation.Rule) *eachKeyRule { 38 mr := eachKeyRule(rules) 39 return &mr 40 } 41 42 // Validate missing godoc 43 func (v eachKeyRule) Validate(value interface{}) error { 44 errs := validation.Errors{} 45 t := reflect.ValueOf(value) 46 if t.Kind() == reflect.Ptr { 47 if t.IsNil() { 48 return nil 49 } 50 t = t.Elem() 51 } 52 53 switch t.Kind() { 54 case reflect.Map: 55 for _, k := range t.MapKeys() { 56 val := getInterface(k) 57 if err := validation.Validate(val, v...); err != nil { 58 errs[getString(k)] = err 59 } 60 } 61 default: 62 return errors.New("the value must be a map") 63 } 64 65 if len(errs) > 0 { 66 return errs 67 } 68 return nil 69 } 70 71 func getInterface(value reflect.Value) interface{} { 72 switch value.Kind() { 73 case reflect.Ptr, reflect.Interface: 74 if value.IsNil() { 75 return nil 76 } 77 return value.Elem().Interface() 78 default: 79 return value.Interface() 80 } 81 } 82 83 func getString(value reflect.Value) string { 84 switch value.Kind() { 85 case reflect.Ptr, reflect.Interface: 86 if value.IsNil() { 87 return "" 88 } 89 return value.Elem().String() 90 default: 91 return value.String() 92 } 93 }