需求具体如下:在Custom Metadata中配置了不同规则的Expression,例如(TRUE AND (FALSE OR TRUE)) is TRUE,(FALSE AND ((TRUE OR FALSE) AND (TRUE OR FALSE)))。 因为规则是动态可配置的,所以我们需要知道在不同的配置下是否满足这个规则,如果满足则返回True,不满足则返回False。
具体代码的实现如下:
/***************************************************************************************************
* Class Name : BooleanExpression
* Created Date : Jan 26, 2021
* Author : He Liu
* Description : Class to evaluate a boolean expression
* Example : (TRUE AND (FALSE OR TRUE)) is TRUE
****************************************************************************************************/
public class BooleanExpression {
static Map<String, String> logicTypes = new Map<String, String>();
static Map<String, Map<String, String>> expressionLogic = new Map<String, Map<String, String>>();
/**
* Evaluate a boolean expreassion
*
*/
public static Boolean eval(String expression) {
// If expression contains all TRUE or FALSE
if(expression.containsNone('FALSE')) { return TRUE; }
if(expression.containsNone('TRUE')) { return FALSE; }
fillLogic();
System.debug('Boolean '+Boolean.valueOf(evaluateExpression(expression.toUpperCase())));
return Boolean.valueOf(evaluateExpression(expression.toUpperCase()));
}
/**
* Evaluate the expression
*
*/
public static String evaluateExpression(String expression) {
for(String logicType : logicTypes.keySet()) {
if(expression.contains(logicType)) {
expression = simplifyExpression(expression, logicTypes.get(logicType));
}
}
if(expression.contains('AND') || expression.contains('OR') || expression.contains('(')) {
expression = evaluateExpression(expression);
}
return expression;
}
/**
* Simplify the expression
*
*/
public static string simplifyExpression(String expression, String LogicType){
Map<String, String> Logic = new Map<String, String>(expressionLogic.get(LogicType));
for(String key : Logic.keySet()) {
expression = expression.replace(key, Logic.get(key));
}
return expression;
}
/**
* Fill AND and OR Logic
*
*/
public static void fillLogic() {
Map<String, String> ANDLogic = new Map<String, String>();
Map<String, String> ORLogic = new Map<String, String>();
Map<String, String> BRACELogic = new Map<String, String>();
logicTypes.put('AND', 'AND');
logicTypes.put('OR', 'OR');
logicTypes.put('(', 'BRACES');
// AND Logic
ANDLogic.put('TRUE AND TRUE', 'TRUE');
ANDLogic.put('TRUE AND FALSE', 'FALSE');
ANDLogic.put('FALSE AND TRUE', 'FALSE');
ANDLogic.put('FALSE AND FALSE', 'FALSE');
expressionLogic.put('AND', ANDLogic);
// OR Logic
ORLogic.put('TRUE OR TRUE', 'TRUE');
ORLogic.put('TRUE OR FALSE', 'TRUE');
ORLogic.put('FALSE OR TRUE', 'TRUE');
ORLogic.put('FALSE OR FALSE', 'FALSE');
expressionLogic.put('OR', ORLogic);
// Braces Logic
BRACELogic.put('(TRUE)', 'TRUE');
BRACELogic.put('(FALSE)', 'FALSE');
expressionLogic.put('BRACES', BRACELogic);
}
}
同样,我们也可以访问下面的链接去看原文的实现:https://vijayasankarn.wordpress.com/2018/07/05/salesforce-apex-evaluate-boolean-string-expression/
网友评论