Skip to content

Commit 4f5b234

Browse files
committed
refactor: Replace string format switch with registry
1 parent eee7ae8 commit 4f5b234

1 file changed

Lines changed: 42 additions & 25 deletions

File tree

src/main/java/com/retailsvc/http/validate/DefaultValidator.java

Lines changed: 42 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,21 @@
3434
import java.util.concurrent.ConcurrentHashMap;
3535
import java.util.concurrent.ConcurrentMap;
3636
import java.util.function.Function;
37+
import java.util.function.Predicate;
3738
import java.util.regex.Pattern;
3839

3940
public final class DefaultValidator implements Validator {
4041

4142
private static final String FORMAT_KEYWORD = "format";
4243

44+
private record FormatCheck(Predicate<String> isValid, String message) {}
45+
46+
private static final Map<String, FormatCheck> FORMAT_CHECKS =
47+
Map.of(
48+
"uuid", new FormatCheck(DefaultValidator::isUuid, "not a valid uuid"),
49+
"date", new FormatCheck(DefaultValidator::isDate, "not a valid date"),
50+
"date-time", new FormatCheck(DefaultValidator::isDateTime, "not a valid date-time"));
51+
4352
private final Function<String, Schema> refResolver;
4453
private final ConcurrentMap<String, Pattern> compiledPatterns = new ConcurrentHashMap<>();
4554

@@ -110,31 +119,39 @@ private void validateString(Object value, StringSchema s, String pointer) {
110119
}
111120

112121
private void validateStringFormat(String str, String format, String pointer) {
113-
switch (format) {
114-
case "uuid" -> {
115-
try {
116-
UUID.fromString(str);
117-
} catch (IllegalArgumentException _) {
118-
fail(pointer, FORMAT_KEYWORD, "not a valid uuid", str);
119-
}
120-
}
121-
case "date" -> {
122-
try {
123-
LocalDate.parse(str);
124-
} catch (DateTimeParseException _) {
125-
fail(pointer, FORMAT_KEYWORD, "not a valid date", str);
126-
}
127-
}
128-
case "date-time" -> {
129-
try {
130-
OffsetDateTime.parse(str);
131-
} catch (DateTimeParseException _) {
132-
fail(pointer, FORMAT_KEYWORD, "not a valid date-time", str);
133-
}
134-
}
135-
default -> {
136-
/* unknown format ignored — handled in 3.1 follow-up */
137-
}
122+
FormatCheck check = FORMAT_CHECKS.get(format);
123+
if (check == null) {
124+
return;
125+
}
126+
if (!check.isValid().test(str)) {
127+
fail(pointer, FORMAT_KEYWORD, check.message(), str);
128+
}
129+
}
130+
131+
private static boolean isUuid(String s) {
132+
try {
133+
UUID.fromString(s);
134+
return true;
135+
} catch (IllegalArgumentException _) {
136+
return false;
137+
}
138+
}
139+
140+
private static boolean isDate(String s) {
141+
try {
142+
LocalDate.parse(s);
143+
return true;
144+
} catch (DateTimeParseException _) {
145+
return false;
146+
}
147+
}
148+
149+
private static boolean isDateTime(String s) {
150+
try {
151+
OffsetDateTime.parse(s);
152+
return true;
153+
} catch (DateTimeParseException _) {
154+
return false;
138155
}
139156
}
140157

0 commit comments

Comments
 (0)