| 
 | 1 | +package formdata  | 
 | 2 | + | 
 | 3 | +import (  | 
 | 4 | +	"fmt"  | 
 | 5 | +	"net/url"  | 
 | 6 | +	"regexp"  | 
 | 7 | + | 
 | 8 | +	"github.com/nuts-foundation/nuts-knooppunt/component/mcsdadmin/valuesets"  | 
 | 9 | +	"github.com/rs/zerolog/log"  | 
 | 10 | +	"github.com/zorgbijjou/golang-fhir-models/fhir-models/fhir"  | 
 | 11 | +)  | 
 | 12 | + | 
 | 13 | +var keyExp regexp.Regexp  | 
 | 14 | + | 
 | 15 | +func init() {  | 
 | 16 | +	exp, err := regexp.Compile(`(\w+)\[(\d*)\]\[(\w+)\]`)  | 
 | 17 | +	if err != nil {  | 
 | 18 | +		log.Error().Err(err).Msg("could not parse regular expression")  | 
 | 19 | +		return  | 
 | 20 | +	}  | 
 | 21 | +	keyExp = *exp  | 
 | 22 | +}  | 
 | 23 | + | 
 | 24 | +func ParseMaps(postform url.Values, fieldName string) []map[string]string {  | 
 | 25 | +	type index = string  | 
 | 26 | +	type key = string  | 
 | 27 | +	type value = string  | 
 | 28 | +	var partials = map[index]map[key]value{}  | 
 | 29 | + | 
 | 30 | +	// Iterate over relevant keys and pull out the relevant data into partials  | 
 | 31 | +	for fk, val := range postform {  | 
 | 32 | +		matches := keyExp.FindStringSubmatch(fk)  | 
 | 33 | +		if len(matches) < 4 {  | 
 | 34 | +			continue  | 
 | 35 | +		}  | 
 | 36 | +		fieldNameMatch := matches[1]  | 
 | 37 | +		indexMatch := matches[2]  | 
 | 38 | +		propKeyMatch := matches[3]  | 
 | 39 | + | 
 | 40 | +		if fieldNameMatch != fieldName {  | 
 | 41 | +			continue  | 
 | 42 | +		}  | 
 | 43 | + | 
 | 44 | +		// Find if we already have some data from other keys...  | 
 | 45 | +		// ... if not create a new map  | 
 | 46 | +		partial, ok := partials[indexMatch]  | 
 | 47 | +		if !ok {  | 
 | 48 | +			partial = map[key]value{}  | 
 | 49 | +			partials[indexMatch] = partial  | 
 | 50 | +		}  | 
 | 51 | + | 
 | 52 | +		if len(val) > 1 {  | 
 | 53 | +			log.Warn().Msg(fmt.Sprintf("conflicting values found for key: %s", fk))  | 
 | 54 | +		}  | 
 | 55 | +		partial[propKeyMatch] = val[0]  | 
 | 56 | +	}  | 
 | 57 | + | 
 | 58 | +	// Now let's construct the return value  | 
 | 59 | +	partialsLen := len(partials)  | 
 | 60 | +	out := make([]map[key]value, 0, partialsLen)  | 
 | 61 | +	for _, part := range partials {  | 
 | 62 | +		out = append(out, part)  | 
 | 63 | +	}  | 
 | 64 | +	return out  | 
 | 65 | +}  | 
 | 66 | + | 
 | 67 | +func CodablesFromForm(postform url.Values, set []fhir.Coding, key string) ([]fhir.CodeableConcept, bool) {  | 
 | 68 | +	nonEmpty := filterEmpty(postform[key])  | 
 | 69 | +	return valuesets.CodablesFrom(set, nonEmpty)  | 
 | 70 | +}  | 
 | 71 | + | 
 | 72 | +func filterEmpty(multiStrings []string) []string {  | 
 | 73 | +	out := make([]string, 0, len(multiStrings))  | 
 | 74 | +	for _, str := range multiStrings {  | 
 | 75 | +		if str != "" {  | 
 | 76 | +			out = append(out, str)  | 
 | 77 | +		}  | 
 | 78 | +	}  | 
 | 79 | +	return out  | 
 | 80 | +}  | 
0 commit comments