1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools.template_engine;
|
---|
3 |
|
---|
4 | import java.util.Arrays;
|
---|
5 | import java.util.stream.Collectors;
|
---|
6 |
|
---|
7 | /**
|
---|
8 | * {@link TemplateEntry} that concatenates several templates.
|
---|
9 | */
|
---|
10 | public final class CompoundTemplateEntry implements TemplateEntry {
|
---|
11 |
|
---|
12 | /**
|
---|
13 | * Factory method to concatenate several {@code TemplateEntry}s.
|
---|
14 | *
|
---|
15 | * If the number of entries is 0 or 1, the result may not be a {@code CompoundTemplateEntry},
|
---|
16 | * but optimized to a static text or the single entry itself.
|
---|
17 | * @param entries the {@code TemplateEntry}s to concatenate
|
---|
18 | * @return a {@link TemplateEntry} that concatenates all the entries
|
---|
19 | */
|
---|
20 | public static TemplateEntry fromArray(TemplateEntry... entries) {
|
---|
21 | if (entries.length == 0)
|
---|
22 | return new StaticText("");
|
---|
23 | else if (entries.length == 1)
|
---|
24 | return entries[0];
|
---|
25 | else
|
---|
26 | return new CompoundTemplateEntry(entries);
|
---|
27 | }
|
---|
28 |
|
---|
29 | private CompoundTemplateEntry(TemplateEntry... entries) {
|
---|
30 | this.entries = entries;
|
---|
31 | }
|
---|
32 |
|
---|
33 | private final TemplateEntry[] entries;
|
---|
34 |
|
---|
35 | @Override
|
---|
36 | public void appendText(StringBuilder result, TemplateEngineDataProvider dataProvider) {
|
---|
37 | for (TemplateEntry te: entries) {
|
---|
38 | te.appendText(result, dataProvider);
|
---|
39 | }
|
---|
40 | }
|
---|
41 |
|
---|
42 | @Override
|
---|
43 | public boolean isValid(TemplateEngineDataProvider dataProvider) {
|
---|
44 | return Arrays.stream(entries).allMatch(te -> te.isValid(dataProvider));
|
---|
45 | }
|
---|
46 |
|
---|
47 | @Override
|
---|
48 | public String toString() {
|
---|
49 | return Arrays.stream(entries).map(String::valueOf).collect(Collectors.joining());
|
---|
50 | }
|
---|
51 |
|
---|
52 | @Override
|
---|
53 | public int hashCode() {
|
---|
54 | return 31 + Arrays.hashCode(entries);
|
---|
55 | }
|
---|
56 |
|
---|
57 | @Override
|
---|
58 | public boolean equals(Object obj) {
|
---|
59 | if (this == obj)
|
---|
60 | return true;
|
---|
61 | if (obj == null || getClass() != obj.getClass())
|
---|
62 | return false;
|
---|
63 | CompoundTemplateEntry other = (CompoundTemplateEntry) obj;
|
---|
64 | return Arrays.equals(entries, other.entries);
|
---|
65 | }
|
---|
66 | }
|
---|