autofixture.implementationdetails.MapBasedRecursionGuard Maven / Gradle / Ivy
package autofixture.implementationdetails;
import autofixture.interfaces.FixtureContract;
import autofixture.interfaces.GeneratorsPipeline;
import autofixture.interfaces.InstanceType;
import autofixture.interfaces.RecursionGuard;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
public class MapBasedRecursionGuard implements RecursionGuard {
private final Map, Integer> recursionCounters = new HashMap<>();
private final GeneratorsPipeline recursionLimitReachedGeneratorsPipeline;
private int maxRecursionDepth;
public MapBasedRecursionGuard(
final int maxRecursionDepth,
final GeneratorsPipeline recursionLimitReachedGeneratorsPipeline) {
this.maxRecursionDepth = maxRecursionDepth;
this.recursionLimitReachedGeneratorsPipeline = recursionLimitReachedGeneratorsPipeline;
}
@Override
public void addDepthLevelTo(final InstanceType instanceType) {
initializeCounterFor(instanceType);
incrementCounterFor(instanceType);
}
@Override
@Nullable
public T defaultValueIfMaxDepthReachedOrGenerateUsing(
final GeneratorsPipeline generatorsPipeline,
final InstanceType instanceType,
final FixtureContract fixture) {
if (maxRecursionDepthIsReachedFor(instanceType)) {
return recursionLimitReachedGeneratorsPipeline.executeFor(instanceType, fixture);
} else {
return generatorsPipeline.executeFor(instanceType, fixture);
}
}
@Override
public void removeDepthLevelFor(final InstanceType instanceType) {
decrementCounterFor(instanceType);
}
private void decrementCounterFor(final InstanceType instanceType) {
Integer counter = recursionCounters.get(instanceType);
counter--;
recursionCounters.put(instanceType, counter);
}
private void incrementCounterFor(final InstanceType instanceType) {
Integer counter = recursionCounters.get(instanceType);
counter++;
recursionCounters.put(instanceType, counter);
}
private boolean maxRecursionDepthIsReachedFor(final InstanceType instanceType) {
initializeCounterFor(instanceType);
return recursionCounters.get(instanceType) > maxRecursionDepth;
}
private void initializeCounterFor(final InstanceType instanceType) {
if (!recursionCounters.containsKey(instanceType)) {
recursionCounters.put(instanceType, 0);
}
}
@Override
public void setMaxDepth(final int maxDepth) {
this.maxRecursionDepth = maxDepth;
}
}