43 lines
1.8 KiB
Java
43 lines
1.8 KiB
Java
package tk.antoine.roux.infrastructure.in;
|
|
|
|
import io.vavr.CheckedFunction1;
|
|
import io.vavr.control.Either;
|
|
import tk.antoine.roux.domain.usecases.ByLabelCriteria;
|
|
import tk.antoine.roux.domain.usecases.ByNameCriteria;
|
|
import tk.antoine.roux.domain.usecases.ByRegexCriteria;
|
|
import tk.antoine.roux.domain.usecases.CriteriaCommand;
|
|
import tk.antoine.roux.domain.usecases.InvalidCriteriaException;
|
|
|
|
import java.util.regex.Pattern;
|
|
|
|
public record Criteria(String rawCriteria) {
|
|
|
|
// https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#dns-subdomain-names
|
|
private static final String RESOURCE_NAME = "^[a-z0-9][a-z0-9-.]{0,252}[a-z0-9]?$";
|
|
private static final String LABEL_RESOURCE = "^[a-z0-9][a-z0-9-./]{0,252}[a-z0-9]?=[a-z0-9][a-z0-9-.]{0,252}[a-z0-9]?$";
|
|
|
|
public Either<Exception, CriteriaCommand> toCommand() {
|
|
String trimmedRawCriteria = rawCriteria.trim();
|
|
final Either<Exception, CriteriaCommand> resultingCriteria;
|
|
|
|
if (trimmedRawCriteria.matches(RESOURCE_NAME)) {
|
|
resultingCriteria = Either.right(new ByNameCriteria(trimmedRawCriteria));
|
|
} else if (trimmedRawCriteria.matches(LABEL_RESOURCE)) {
|
|
resultingCriteria = Either.right(new ByLabelCriteria());
|
|
} else if (isAValidRegex(trimmedRawCriteria)) {
|
|
resultingCriteria = Either.right(new ByRegexCriteria(Pattern.compile(trimmedRawCriteria)));
|
|
} else {
|
|
resultingCriteria = Either.left(new InvalidCriteriaException("not a word", this));
|
|
}
|
|
return resultingCriteria;
|
|
}
|
|
|
|
private boolean isAValidRegex(String value) {
|
|
return CheckedFunction1.<String, Pattern>liftTry(Pattern::compile)
|
|
.apply(value)
|
|
.map(pattern -> true)
|
|
.getOrElse(false);
|
|
}
|
|
|
|
}
|