generateEnum<T extends Object?> method

void generateEnum<T extends Object?>(
  1. StringBuffer buffer,
  2. Iterable<ClassModel> models
)

Generate enums for the data classes file.

Implementation

void generateEnum<T extends Object?>(
  final StringBuffer buffer,
  final Iterable<ClassModel> models,
) {
  final Set<String> processedEnumNames = <String>{};
  for (final ClassModel model in models) {
    for (final FieldModel field in model.fields) {
      if (field.reference.isEmpty ||
          (field.type != FieldType.$enum && field.type != FieldType.$$enum)) {
        continue;
      }

      final String enumName =
          _renderType(model, field, iterable: false, nullable: false);
      if (processedEnumNames.contains(enumName)) {
        continue;
      }
      processedEnumNames.add(enumName);

      String reference = field.reference.split('[').last;
      if (reference.endsWith(']')) {
        reference = reference.substring(0, reference.length - 1);
      }
      buffer
        ..writeDoc('The enum for the [${model.name}.${field.name}].')
        ..writeln('enum $enumName { ');
      final Iterable<String> referenceValues =
          reference.split(',').map((final _) => _.trim());
      for (int index = 0; index < referenceValues.length; index++) {
        final String value = referenceValues.elementAt(index);
        buffer
          ..writeDoc('The `$value` property of this [$enumName].', indent: 2)
          ..write(field.convert ? value.toCamelCase() : value.normalize())
          ..writeln(index < referenceValues.length - 1 ? ',' : ';');
      }
      if (referenceValues.any(
        (final _) => _ != (field.convert ? _.toCamelCase() : _.normalize()),
      )) {
        buffer
          ..writeln()
          ..writeDoc('The name of the enum value.', indent: 2)
          ..writeln('String get name {')
          ..writeln('switch (this) {');
        for (final String value in referenceValues) {
          final String $value =
              field.convert ? value.toCamelCase() : value.normalize();
          buffer
            ..writeln('case ${$value}:')
            ..writeln("return '$value';");
        }
        buffer
          ..writeln('}')
          ..writeln('}');
      }
      buffer.writeln('}');
    }
  }
}