TemplateImpl   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 3
eloc 20
dl 0
loc 24
rs 10
c 2
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A TemplateImpl(String) 0 2 1
A apply(Map) 0 17 2
1
package com.osomapps.pt.tokenemail;
2
3
import java.util.HashMap;
4
import java.util.Map;
5
6
final class TemplateEngine {
7
    private static final String ALL_SYMBOLS = "([\\s\\S]+?)";
8
    private static final Map<String, String> TEMPLATE_SETTINGS = new HashMap<>();
9
10
    static {
11
        TEMPLATE_SETTINGS.put("evaluate", "\\{\\{" + ALL_SYMBOLS + "\\}\\}");
12
    }
13
14
    interface Template<F> {
15
        String apply(F arg);
16
    }
17
18
    static final class TemplateImpl<K, V> implements Template<Map<K, V>> {
19
        private final String template;
20
21
        TemplateImpl(String template) {
22
            this.template = template;
23
        }
24
25
        @Override
26
        public String apply(Map<K, V> value) {
27
            final String evaluate = TEMPLATE_SETTINGS.get("evaluate");
28
            String result = template;
29
            for (final Map.Entry<K, V> element : value.entrySet()) {
30
                result =
31
                        java.util.regex.Pattern.compile(
32
                                        evaluate.replace(
33
                                                ALL_SYMBOLS,
34
                                                "\\s*"
35
                                                        + java.util.regex.Pattern.quote(
36
                                                                String.valueOf(element.getKey()))
37
                                                        + "\\s*"))
38
                                .matcher(result)
39
                                .replaceAll(String.valueOf(element.getValue()));
40
            }
41
            return result;
42
        }
43
    }
44
45
    static <K, V> TemplateEngine.Template<Map<K, V>> template(final String template) {
46
        return new TemplateImpl<>(template);
47
    }
48
}
49