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 int maxRecursionDepth;
public MapBasedRecursionGuard(
final int maxRecursionDepth) {
this.maxRecursionDepth = maxRecursionDepth;
}
@Override
public void addDepthLevelTo(final InstanceType instanceType) {
initializeCounterFor(instanceType);
incrementCounterFor(instanceType);
}
@Override
@Nullable
public T generateUsing(
final GeneratorsPipeline generatorsPipeline,
final InstanceType instanceType,
final FixtureContract fixture) {
if (maxRecursionDepthIsReachedFor(instanceType)) {
return generatorsPipeline.generateEmptyInstanceOf(instanceType, fixture);
} else {
return generatorsPipeline.generateInstanceOf(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;
}
}