tcr/java/src/game/command/StringParser.java
2025-03-19 21:54:09 +01:00

45 lines
1.8 KiB
Java

package game.command;
import game.util.CharValidator;
public class StringParser extends DefaultingParser {
private final boolean allowEmpty;
private final Integer minLength;
private final Integer maxLength;
private final CharValidator validator;
public StringParser(String name, String def, boolean allowEmpty, Integer minLength, Integer maxLength, CharValidator validator,
Object ... completions) {
super(name, def, completions);
this.allowEmpty = allowEmpty;
this.minLength = minLength;
this.maxLength = maxLength;
this.validator = validator;
}
public String parse(ScriptEnvironment env, String input) {
if(!this.allowEmpty && input.isEmpty())
throw new ScriptException("Die Zeichenkette darf nicht leer sein");
if(this.minLength != null && input.length() < this.minLength)
if(this.maxLength != null)
throw new ScriptException("Die Zeichenkette muss zwischen %d .. %d Zeichen lang sein, habe %d ('%s')",
this.minLength, this.maxLength, input.length(), input);
else
throw new ScriptException("Die Zeichenkette muss mindestens %d Zeichen lang sein, habe %d ('%s')",
this.minLength, input.length(), input);
if(this.maxLength != null && input.length() > this.maxLength)
if(this.minLength != null)
throw new ScriptException("Die Zeichenkette muss zwischen %d .. %d Zeichen lang sein, habe %d ('%s')",
this.minLength, this.maxLength, input.length(), input);
else
throw new ScriptException("Die Zeichenkette darf höchstens %d Zeichen lang sein, habe %d ('%s')",
this.maxLength, input.length(), input);
if(this.validator != null && !this.validator.valid(input))
throw new ScriptException("Die Zeichenkette '%s' enthält ungültige Zeichen", input);
return input;
}
public Class<?> getTypeClass() {
return String.class;
}
}