Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make config enums ignore case #76

Merged
merged 1 commit into from
Oct 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -353,14 +353,20 @@ public void load(@Nullable Object instance, @Nullable String defValueString, Fie
langKey);

try {
boolean saveOnExit = false;
if (!Arrays.asList(possibleValues).contains(value)) {
throw new NoSuchFieldException();
value = Optional.ofNullable(getEnumIgnoredCase(value, possibleValues))
.orElseThrow(NoSuchFieldException::new);
saveOnExit = true;
}
Field enumField = fieldClass.getDeclaredField(value);
if (!enumField.isEnumConstant()) {
throw new NoSuchFieldException();
}
field.set(instance, enumField.get(instance));
if (saveOnExit) {
save(instance, field, config, category, name);
}
} catch (NoSuchFieldException e) {
ConfigurationManager.LOGGER.warn(
"Invalid value {} for enum configuration field {} of type {} in config class {}! Using default value of {}!",
Expand All @@ -370,6 +376,7 @@ public void load(@Nullable Object instance, @Nullable String defValueString, Fie
field.getDeclaringClass().getName(),
defaultValue);
field.set(instance, defaultValue);
save(instance, field, config, category, name);
}
}

Expand Down Expand Up @@ -399,6 +406,15 @@ private Enum<?> fromStringOrDefault(@Nullable Object instance, @Nullable String

return value;
}

private @Nullable String getEnumIgnoredCase(String value, String[] validValues) {
for (String valid : validValues) {
if (valid.equalsIgnoreCase(value)) {
return valid;
}
}
return null;
}
}

private static class StringArrayParser implements Parser {
Expand Down