github.com/Axway/agent-sdk@v1.1.101/pkg/filter/condition.go (about)

     1  package filter
     2  
     3  import (
     4  	"go/token"
     5  	"strconv"
     6  )
     7  
     8  // Condition - Interface for the filter condition
     9  type Condition interface {
    10  	Evaluate(data Data) bool
    11  	String() string
    12  }
    13  
    14  // SimpleCondition - Identifies a simple condition
    15  type SimpleCondition struct {
    16  	LHSExpr  CallExpr
    17  	Value    ComparableValue
    18  	Operator string
    19  }
    20  
    21  // Evaluate - evaluates a simple/call expression condition
    22  func (sf *SimpleCondition) Evaluate(data Data) (res bool) {
    23  	lhsValue, err := sf.LHSExpr.Execute(data)
    24  	if err != nil {
    25  		return false
    26  	}
    27  	callType := sf.LHSExpr.GetType()
    28  	switch callType {
    29  	case ANY:
    30  		if sf.Value != nil {
    31  			res = sf.Value.any(lhsValue)
    32  			if sf.Operator == token.NEQ.String() {
    33  				res = !res
    34  			}
    35  		}
    36  	default:
    37  		if callType != GETVALUE {
    38  			res = lhsValue.(bool)
    39  			lhsValue = strconv.FormatBool(res)
    40  		}
    41  
    42  		if sf.Operator != "" && sf.Value != nil {
    43  			if sf.Operator == token.EQL.String() {
    44  				res = sf.Value.eq(lhsValue)
    45  			} else if sf.Operator == token.NEQ.String() {
    46  				res = sf.Value.neq(lhsValue)
    47  			}
    48  		}
    49  	}
    50  
    51  	return res
    52  }
    53  
    54  // String - string representation for simple condition
    55  func (sf *SimpleCondition) String() string {
    56  	str := sf.LHSExpr.String()
    57  	if sf.Operator != "" {
    58  		str += " " + sf.Operator
    59  	}
    60  	if sf.Value != nil && sf.Value.String() != "" {
    61  		str += " " + sf.Value.String()
    62  	}
    63  	return "(" + str + ")"
    64  }
    65  
    66  // CompoundCondition - Represents group of simple conditions
    67  type CompoundCondition struct {
    68  	RHSCondition Condition
    69  	LHSCondition Condition
    70  	Operator     string
    71  }
    72  
    73  // Evaluate - evaulates the compound condition
    74  func (cf *CompoundCondition) Evaluate(data Data) bool {
    75  	lhsRes := cf.LHSCondition.Evaluate(data)
    76  	rhsRes := cf.RHSCondition.Evaluate(data)
    77  	if cf.Operator == token.LOR.String() {
    78  		return (lhsRes || rhsRes)
    79  	}
    80  	return (lhsRes && rhsRes)
    81  }
    82  
    83  // String - string representation for compound condition
    84  func (cf *CompoundCondition) String() string {
    85  	if cf.RHSCondition != nil && cf.LHSCondition != nil {
    86  		return "(" + cf.LHSCondition.String() + " " + cf.Operator + " " + cf.RHSCondition.String() + ")"
    87  	}
    88  	return ""
    89  }