Skip to content

Commit

Permalink
Implement context arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
Alemiz112 committed Mar 25, 2023
1 parent ec6fd7c commit c86958f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public String getText(T object) {
formatted = formatted.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue().apply(ctx));
}
}
return formatted;
return ctx.handlePostFormat(formatted);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package eu.mizerak.alemiz.translationlib.common.string;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;

public abstract class TranslationContext<T> {
private final T object;
private Map<String, Function<T, String>> localArguments;

public TranslationContext(T object) {
this.object = object;
Expand All @@ -15,6 +19,27 @@ public T getObject() {
return this.object;
}

public TranslationContext<T> argument(String argument, Object value) {
return this.argument(argument, t -> String.valueOf(value));
}

public TranslationContext<T> argument(String argument, Function<T, String> function) {
if (this.localArguments == null) {
this.localArguments = new HashMap<>();
}
this.localArguments.put(argument, function);
return this;
}

public String handlePostFormat(String string) {
if (this.localArguments != null) {
for (Map.Entry<String, Function<T, String>> entry : this.localArguments.entrySet()) {
string = string.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue().apply(this.object));
}
}
return string;
}

public interface Factory<T> {
TranslationContext<T> create(T object);
}
Expand Down

0 comments on commit c86958f

Please sign in to comment.