Introduce FluxMapNotNull{,Transformation}OrElse Refaster rules (#1493)

This commit is contained in:
Phil Werli
2025-01-02 12:42:25 +01:00
committed by GitHub
parent 7f90f26830
commit e67800e4e2
3 changed files with 48 additions and 0 deletions

View File

@@ -889,6 +889,38 @@ final class ReactorRules {
}
}
/**
* Prefer immediately unwrapping {@link Optional} transformation results inside {@link
* Flux#mapNotNull(Function)} over more contrived alternatives.
*/
abstract static class FluxMapNotNullTransformationOrElse<T, S> {
@Placeholder(allowsIdentity = true)
abstract Optional<S> transformation(@MayOptionallyUse T value);
@BeforeTemplate
Flux<S> before(Flux<T> flux) {
return flux.map(v -> transformation(v)).mapNotNull(o -> o.orElse(null));
}
@AfterTemplate
Flux<S> after(Flux<T> flux) {
return flux.mapNotNull(x -> transformation(x).orElse(null));
}
}
/** Prefer {@link Flux#mapNotNull(Function)} over more contrived alternatives. */
static final class FluxMapNotNullOrElse<T> {
@BeforeTemplate
Flux<T> before(Flux<Optional<T>> flux) {
return flux.filter(Optional::isPresent).map(Optional::orElseThrow);
}
@AfterTemplate
Flux<T> after(Flux<Optional<T>> flux) {
return flux.mapNotNull(x -> x.orElse(null));
}
}
/** Prefer {@link Mono#flux()}} over more contrived alternatives. */
static final class MonoFlux<T> {
@BeforeTemplate

View File

@@ -325,6 +325,14 @@ final class ReactorRulesTest implements RefasterRuleCollectionTestCase {
Flux.just(1).switchMap(n -> Mono.fromSupplier(() -> n * 2)));
}
Flux<String> testFluxMapNotNullTransformationOrElse() {
return Flux.just(1).map(x -> Optional.of(x.toString())).mapNotNull(x -> x.orElse(null));
}
Flux<Integer> testFluxMapNotNullOrElse() {
return Flux.just(Optional.of(1)).filter(Optional::isPresent).map(Optional::orElseThrow);
}
ImmutableSet<Flux<String>> testMonoFlux() {
return ImmutableSet.of(
Mono.just("foo").flatMapMany(Mono::just),

View File

@@ -325,6 +325,14 @@ final class ReactorRulesTest implements RefasterRuleCollectionTestCase {
Flux.just(1).mapNotNull(n -> n * 2));
}
Flux<String> testFluxMapNotNullTransformationOrElse() {
return Flux.just(1).mapNotNull(x -> Optional.of(x.toString()).orElse(null));
}
Flux<Integer> testFluxMapNotNullOrElse() {
return Flux.just(Optional.of(1)).mapNotNull(x -> x.orElse(null));
}
ImmutableSet<Flux<String>> testMonoFlux() {
return ImmutableSet.of(
Mono.just("foo").flux(), Mono.just("bar").flux(), Mono.just("baz").flux());