1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools.template_engine;
|
---|
3 |
|
---|
4 | import java.util.ArrayList;
|
---|
5 | import java.util.Collection;
|
---|
6 | import java.util.List;
|
---|
7 |
|
---|
8 | /**
|
---|
9 | * {@link TemplateEntry} that applies other templates based on conditions.
|
---|
10 | * <p>
|
---|
11 | * It goes through a number of template entries and executes the first one that is valid.
|
---|
12 | */
|
---|
13 | public class Condition implements TemplateEntry {
|
---|
14 |
|
---|
15 | private final List<TemplateEntry> entries;
|
---|
16 |
|
---|
17 | /**
|
---|
18 | * Constructs a new {@code Condition} with predefined template entries.
|
---|
19 | * @param entries template entries
|
---|
20 | */
|
---|
21 | public Condition(Collection<TemplateEntry> entries) {
|
---|
22 | this.entries = new ArrayList<>(entries);
|
---|
23 | }
|
---|
24 |
|
---|
25 | /**
|
---|
26 | * Constructs a new {@code Condition}.
|
---|
27 | */
|
---|
28 | public Condition() {
|
---|
29 | this.entries = new ArrayList<>();
|
---|
30 | }
|
---|
31 |
|
---|
32 | @Override
|
---|
33 | public void appendText(StringBuilder result, TemplateEngineDataProvider dataProvider) {
|
---|
34 | for (TemplateEntry entry: entries) {
|
---|
35 | if (entry.isValid(dataProvider)) {
|
---|
36 | entry.appendText(result, dataProvider);
|
---|
37 | return;
|
---|
38 | }
|
---|
39 | }
|
---|
40 |
|
---|
41 | // Fallback to last entry
|
---|
42 | TemplateEntry entry = entries.get(entries.size() - 1);
|
---|
43 | entry.appendText(result, dataProvider);
|
---|
44 | }
|
---|
45 |
|
---|
46 | @Override
|
---|
47 | public boolean isValid(TemplateEngineDataProvider dataProvider) {
|
---|
48 |
|
---|
49 | for (TemplateEntry entry: entries) {
|
---|
50 | if (entry.isValid(dataProvider))
|
---|
51 | return true;
|
---|
52 | }
|
---|
53 |
|
---|
54 | return false;
|
---|
55 | }
|
---|
56 |
|
---|
57 | @Override
|
---|
58 | public String toString() {
|
---|
59 | StringBuilder sb = new StringBuilder();
|
---|
60 | sb.append("?{ ");
|
---|
61 | for (TemplateEntry entry: entries) {
|
---|
62 | if (entry instanceof SearchExpressionCondition) {
|
---|
63 | sb.append(entry);
|
---|
64 | } else {
|
---|
65 | sb.append('\'').append(entry).append('\'');
|
---|
66 | }
|
---|
67 | sb.append(" | ");
|
---|
68 | }
|
---|
69 | sb.setLength(sb.length() - 3);
|
---|
70 | sb.append(" }");
|
---|
71 | return sb.toString();
|
---|
72 | }
|
---|
73 | }
|
---|