Total Complexity | 1 |
Total Lines | 41 |
Duplicated Lines | 0 % |
Changes | 3 | ||
Bugs | 0 | Features | 0 |
1 | package com.osomapps.pt.tokenemail; |
||
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 | } |
||
49 |