writeBeanFactory static method

void writeBeanFactory(
  1. ClassElement element,
  2. StructurizeResult structurized,
  3. SubjectCodeContext codeContext
)

Implementation

static void writeBeanFactory(ClassElement element,
    StructurizeResult structurized, SubjectCodeContext codeContext) {
  var emitter = DartEmitter();
  var factoryName = "${element.name}Factory";
  var clazz = Class((builder) {
    builder.name = factoryName;
    builder.methods.add(Method((builder) {
      builder.optionalParameters.addAll(structurized.structure.fields
          .map((e) => Parameter((builder) => builder
            ..named = true
            ..required = !e.optional
            ..type = Reference(e.type + (e.optional ? "?" : ""))
            ..name = e.name)));

      builder
        ..name = "create"
        ..returns = Reference(codeContext.className(element))
        ..static = true
        ..lambda = false
        ..body = Code(
            "var obj = ${codeContext.className(element)}();${structurized.structure.fields.mapIndexed((i, e) => "obj.${e.name} = ${e.name};").join("\n")} return obj;");
    }));
  });

  codeContext.codeBuffer.writeln(clazz.accept(emitter));
}