Passed
Push — main ( e3287a...08aeb5 )
by Hao
03:41
created

io.github.ro4.check.SpELChecker   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0
eloc 18
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A SpELChecker() 0 1 1
A SpELChecker(BeanFactory) 0 2 1
A pass(Context) 0 16 5
1
package io.github.ro4.check;
2
3
import io.github.ro4.ExpressionException;
4
import io.github.ro4.constant.MagicMark;
5
import io.github.ro4.Context;
6
import org.springframework.beans.factory.BeanFactory;
7
import org.springframework.context.expression.BeanFactoryResolver;
8
import org.springframework.expression.spel.standard.SpelExpressionParser;
9
import org.springframework.expression.spel.support.StandardEvaluationContext;
10
11 1
public class SpELChecker implements Checker {
12 1
    private static final SpelExpressionParser PARSER = new SpelExpressionParser();
13
14 1
    private BeanFactory beanFactory = null;
15
16 1
    public SpELChecker() {
17
18 1
    }
19
20 1
    public SpELChecker(BeanFactory beanFactory) {
21 1
        this.beanFactory = beanFactory;
22 1
    }
23
24
    @Override
25
    public boolean pass(Context ctx) {
26 1
        if (!ctx.hasAttribute(MagicMark.EXPRESSION)) {
27 1
            throw new ExpressionException("expression not found");
28
        }
29 1
        StandardEvaluationContext spELCtx = new StandardEvaluationContext();
30
        // ugly design, temporary work
31 1
        if (null != beanFactory) {
32 1
            spELCtx.setBeanResolver(new BeanFactoryResolver(beanFactory));
33
        }
34 1
        for (String s : ctx.attributeNames()) {
35 1
            spELCtx.setVariable(s, ctx.getAttribute(s));
36
        }
37 1
        String expression = (String) ctx.getAttribute(MagicMark.EXPRESSION);
38 1
        assert expression != null;
39 1
        return Boolean.TRUE.equals(PARSER.parseExpression(expression).getValue(spELCtx, Boolean.TYPE));
40
    }
41
}
42