package cn.axzo.workflow.common.util;

import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Properties;

/**
 * 处理字符串中含有变量的字符串
 *
 * @author wangli
 * @since 2024-11-15 17:57
 */
public abstract class ExpressionUtil {
    private static final String PREFIX = "${";
    private static final String SUFFIX = "}";

    private ExpressionUtil() {
        throw new RuntimeException("Instantiation not supported");
    }

    public static String parseString(String exp, Map<String, ? extends Object> variables) {
        return parseString(null, null, exp, variables);
    }

    public static String parseString(String prefix, String suffix, String exp, Map<String, ? extends Object> variables) {
        if (!StringUtils.hasText(prefix) && !StringUtils.hasText(suffix)) {
            prefix = PREFIX;
            suffix = SUFFIX;
        }
        PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper(prefix, suffix);
        Properties properties = new Properties();
        variables.forEach((k, v) -> properties.setProperty(k, String.valueOf(v)));

        // 自定义PlaceholderResolver实现类，用于处理占位符找不到对应值时返回空字符串
        PropertyPlaceholderHelper.PlaceholderResolver resolver = placeholder -> properties.getProperty(placeholder, "");
        return propertyPlaceholderHelper.replacePlaceholders(exp, resolver);
    }
}
