github.com/safing/portbase@v0.19.5/database/query/condition-stringslice.go (about)

     1  package query
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/safing/portbase/database/accessor"
     8  	"github.com/safing/portbase/utils"
     9  )
    10  
    11  type stringSliceCondition struct {
    12  	key      string
    13  	operator uint8
    14  	value    []string
    15  }
    16  
    17  func newStringSliceCondition(key string, operator uint8, value interface{}) *stringSliceCondition {
    18  	switch v := value.(type) {
    19  	case string:
    20  		parsedValue := strings.Split(v, ",")
    21  		if len(parsedValue) < 2 {
    22  			return &stringSliceCondition{
    23  				key:      v,
    24  				operator: errorPresent,
    25  			}
    26  		}
    27  		return &stringSliceCondition{
    28  			key:      key,
    29  			operator: operator,
    30  			value:    parsedValue,
    31  		}
    32  	case []string:
    33  		return &stringSliceCondition{
    34  			key:      key,
    35  			operator: operator,
    36  			value:    v,
    37  		}
    38  	default:
    39  		return &stringSliceCondition{
    40  			key:      fmt.Sprintf("incompatible value %v for []string", value),
    41  			operator: errorPresent,
    42  		}
    43  	}
    44  }
    45  
    46  func (c *stringSliceCondition) complies(acc accessor.Accessor) bool {
    47  	comp, ok := acc.GetString(c.key)
    48  	if !ok {
    49  		return false
    50  	}
    51  
    52  	switch c.operator {
    53  	case In:
    54  		return utils.StringInSlice(c.value, comp)
    55  	default:
    56  		return false
    57  	}
    58  }
    59  
    60  func (c *stringSliceCondition) check() error {
    61  	if c.operator == errorPresent {
    62  		return fmt.Errorf("could not parse \"%s\" to []string", c.key)
    63  	}
    64  	return nil
    65  }
    66  
    67  func (c *stringSliceCondition) string() string {
    68  	return fmt.Sprintf("%s %s %s", escapeString(c.key), getOpName(c.operator), escapeString(strings.Join(c.value, ",")))
    69  }