package generators;
import ast.*;
import models.dataConstraintModel.MapType;
public class DependencyInversionWeaver {
static void replaceDepedencyInClass(Codebase codebase, TypeDeclaration srcClass, models.algebra.Type dstType, models.algebra.Type interfaceType, String interfaceName) {
for (FieldDeclaration field: srcClass.getFields()) {
if (field.getType().equals(dstType)) {
// private Companies companies → private ICompanies companies
field.setType(interfaceType);
} else if (field.getType() instanceof MapType) {
MapType mapType = (MapType) field.getType();
// Map<String, Companies> → Map<String, ICompanies>
if (mapType.getValueType() != null && mapType.getValueType().getTypeName().equals(dstType.getTypeName())) {
field.setType(codebase.getMapType(mapType.getKeyType().getTypeName(), interfaceName));
}
}
}
for (MethodDeclaration method: srcClass.getMethods()) {
// Change constructor parameter types
if (method.isConstructor() && method.getParameters() != null) {
for (VariableDeclaration param: method.getParameters()) {
if (param.getType() != null && param.getType().equals(dstType)) {
// Customer(Companies companies) → Customer(ICompanies companies)
param.setType(interfaceType);
}
}
}
if (!method.isConstructor() && method.getParameters() != null) {
for (VariableDeclaration param: method.getParameters()) {
if (param.getType() != null && param.getType().equals(dstType)) {
param.setType(interfaceType);
}
}
}
// Change method return types
if (!method.isConstructor() && method.getReturnType() != null) {
if (method.getReturnType().getTypeName().equals(dstType.getTypeName())) {
// public Company getCompany() → public ICompany getCompany()
method.setReturnType(interfaceType);
}
}
}
}
public static InterfaceDeclaration createInterface(Codebase codebase, String name) {
if (codebase.getInterfaceCompilationUnit(name) != null) {
return codebase.getInterfaceCompilationUnit(name).interfaces().getFirst();
}
InterfaceDeclaration interfaceDeclaration = new InterfaceDeclaration(name);
CompilationUnit compilationUnit = new CompilationUnit(interfaceDeclaration);
codebase.addInterfaceCompilationUnit(name, compilationUnit);
return interfaceDeclaration;
}
}