diff --git a/lib/src/code_generators/swagger_enums_generator.dart b/lib/src/code_generators/swagger_enums_generator.dart index 7156fd92..5952f5aa 100644 --- a/lib/src/code_generators/swagger_enums_generator.dart +++ b/lib/src/code_generators/swagger_enums_generator.dart @@ -1,9 +1,9 @@ import 'package:collection/collection.dart'; -import 'package:recase/recase.dart'; import 'package:swagger_dart_code_generator/src/code_generators/constants.dart'; import 'package:swagger_dart_code_generator/src/code_generators/enum_model.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_generator_base.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_requests_generator.dart'; +import 'package:swagger_dart_code_generator/src/code_generators/utils.dart'; import 'package:swagger_dart_code_generator/src/code_generators/v2/swagger_models_generator_v2.dart'; import 'package:swagger_dart_code_generator/src/extensions/string_extension.dart'; import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; @@ -34,8 +34,7 @@ abstract class SwaggerEnumsGenerator extends SwaggerGeneratorBase { required String fileName, }) { final requestBodies = root.components?.requestBodies ?? {}; - requestBodies.addAll( - SwaggerModelsGeneratorV2(options).getRequestBodiesFromRequests(root)); + requestBodies.addAll(SwaggerModelsGeneratorV2(options).getRequestBodiesFromRequests(root)); final formattedRequestBodies = {}; requestBodies.forEach((key, value) { @@ -53,13 +52,12 @@ abstract class SwaggerEnumsGenerator extends SwaggerGeneratorBase { final enumsFromRequests = generateEnumsContentFromRequests(root, fileName); final enumsFromResponses = generateEnumsFromSchemaMap(formattedResponses); - final enumsFromRequestBodies = - generateEnumsFromSchemaMap(formattedRequestBodies); + final enumsFromRequestBodies = generateEnumsFromSchemaMap(formattedRequestBodies); final enumsFromClasses = definitions.keys .map((String className) { final result = generateEnumsFromClasses( - getValidatedClassName(className.pascalCase), + getValidatedClassName(className.toClassName), definitions[className]!, definitions, ); @@ -112,7 +110,7 @@ ${allEnums.map((e) => e.toString()).join('\n')} } return generateEnumsFromClasses( - getValidatedClassName(className.pascalCase), + getValidatedClassName(className.toClassName), schema, {}, ); @@ -121,8 +119,7 @@ ${allEnums.map((e) => e.toString()).join('\n')} .toList(); } - List generateEnumsContentFromRequests( - SwaggerRoot swaggerRoot, String fileName) { + List generateEnumsContentFromRequests(SwaggerRoot swaggerRoot, String fileName) { final result = []; final definedParameters = {}; @@ -136,12 +133,10 @@ ${allEnums.map((e) => e.toString()).join('\n')} final enumNames = swaggerRequestParameter.schema?.enumNames ?? []; - final isInteger = - kIntegerTypes.contains(swaggerRequestParameter.schema?.type) || - kIntegerTypes.contains(swaggerRequestParameter.items?.type); + final isInteger = kIntegerTypes.contains(swaggerRequestParameter.schema?.type) || + kIntegerTypes.contains(swaggerRequestParameter.items?.type); - if (enumValues.isNotEmpty && - swaggerRoot.components?.schemas.containsKey(key) != true) { + if (enumValues.isNotEmpty && swaggerRoot.components?.schemas.containsKey(key) != true) { final enumContent = EnumModel( name: getValidatedClassName(key), values: enumValues, @@ -154,19 +149,16 @@ ${allEnums.map((e) => e.toString()).join('\n')} }); swaggerRoot.paths.forEach((String path, SwaggerPath swaggerPath) { - swaggerPath.requests - .forEach((String requestType, SwaggerRequest swaggerRequest) { - final successResponses = SwaggerRequestsGenerator.getSuccessedResponses( - responses: swaggerRequest.responses); + swaggerPath.requests.forEach((String requestType, SwaggerRequest swaggerRequest) { + final successResponses = + SwaggerRequestsGenerator.getSuccessedResponses(responses: swaggerRequest.responses); for (final successResponse in successResponses) { - final successResponseSchema = - successResponse.schema ?? successResponse.content?.schema; + final successResponseSchema = successResponse.schema ?? successResponse.content?.schema; if (successResponseSchema != null) { final responseEnums = generateEnumsFromSchemaMap({ - '${path.pascalCase}${requestType.pascalCase}\$$kResponse': - successResponseSchema + '${path.toClassName}${requestType.toClassName}\$$kResponse': successResponseSchema }); result.addAll(responseEnums); } @@ -184,8 +176,7 @@ ${allEnums.map((e) => e.toString()).join('\n')} for (var p = 0; p < parameters.length; p++) { final swaggerRequestParameter = parameters[p]; - var name = generateRequestEnumName( - path, requestType, swaggerRequestParameter.name); + var name = generateRequestEnumName(path, requestType, swaggerRequestParameter.name); name = getValidatedClassName(name); @@ -201,9 +192,8 @@ ${allEnums.map((e) => e.toString()).join('\n')} final enumNames = swaggerRequestParameter.schema?.enumNames ?? []; - final isInteger = - kIntegerTypes.contains(swaggerRequestParameter.schema?.type) || - kIntegerTypes.contains(swaggerRequestParameter.items?.type); + final isInteger = kIntegerTypes.contains(swaggerRequestParameter.schema?.type) || + kIntegerTypes.contains(swaggerRequestParameter.items?.type); if (enumValues.isNotEmpty) { final enumContent = EnumModel( @@ -243,13 +233,12 @@ ${allEnums.map((e) => e.toString()).join('\n')} final result = []; if (properties.isNotEmpty) { - final isListProperty = - enumValues.items?.properties.isNotEmpty == true; + final isListProperty = enumValues.items?.properties.isNotEmpty == true; result.addAll( generateEnumsContentFromModelProperties( properties, - '$className\$${key.pascalCase}${isListProperty ? '\$Item' : ''}', + '$className\$${key.toClassName}${isListProperty ? '\$Item' : ''}', ), ); } @@ -283,8 +272,7 @@ ${allEnums.map((e) => e.toString()).join('\n')} return enumValues.isNotEmpty && enumValues.first is int; } - EnumModel? generateEnumContentIfPossible( - SwaggerSchema schema, String enumName) { + EnumModel? generateEnumContentIfPossible(SwaggerSchema schema, String enumName) { enumName = getValidatedClassName(enumName); if (schema.isEnum) { @@ -320,8 +308,7 @@ ${allEnums.map((e) => e.toString()).join('\n')} if (schema.items != null) { if (schema.items!.isEnum) { - final enumModel = - generateEnumContentIfPossible(schema.items!, className); + final enumModel = generateEnumContentIfPossible(schema.items!, className); return enumModel == null ? [] : [enumModel]; } @@ -329,8 +316,8 @@ ${allEnums.map((e) => e.toString()).join('\n')} var result = []; schema.items?.properties.forEach((key, value) { - final enumModel = generateEnumContentIfPossible( - value, '$className\$Item${key.pascalCase}'); + final enumModel = + generateEnumContentIfPossible(value, '$className\$Item${key.toClassName}'); if (enumModel != null) { result.add(enumModel); } @@ -366,8 +353,7 @@ ${allEnums.map((e) => e.toString()).join('\n')} final allOfModel = schemas[ref.getUnformattedRef()]; if (allOfModel?.allOf.isNotEmpty == true) { - final allOfRef = - allOfModel?.allOf.firstWhereOrNull((e) => e.hasRef)?.ref ?? ''; + final allOfRef = allOfModel?.allOf.firstWhereOrNull((e) => e.hasRef)?.ref ?? ''; final allOfModelInside = schemas[allOfRef.getUnformattedRef()]; properties.addAll(allOfModelInside?.properties ?? {}); diff --git a/lib/src/code_generators/swagger_generator_base.dart b/lib/src/code_generators/swagger_generator_base.dart index db820dce..f2248272 100644 --- a/lib/src/code_generators/swagger_generator_base.dart +++ b/lib/src/code_generators/swagger_generator_base.dart @@ -1,5 +1,6 @@ import 'package:recase/recase.dart'; import 'package:swagger_dart_code_generator/src/code_generators/constants.dart'; +import 'package:swagger_dart_code_generator/src/code_generators/utils.dart'; import 'package:swagger_dart_code_generator/src/exception_words.dart'; import 'package:swagger_dart_code_generator/src/extensions/string_extension.dart'; import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; @@ -36,10 +37,7 @@ abstract class SwaggerGeneratorBase { final words = className.split('\$'); final result = words - .map((e) => e.pascalCase - .split(RegExp(r'\W+|\_')) - .map((String str) => str.capitalize) - .join()) + .map((e) => e.toClassName.split(RegExp(r'\W+')).map((String str) => str.capitalize).join()) .join('\$') .replaceFirst(RegExp(options.cutFromModelNames), ''); @@ -55,17 +53,14 @@ abstract class SwaggerGeneratorBase { return '\$$result'; } - return result - .replaceFirst(options.cutFromModelNames, '') - .replaceAll('\$\$', '\$'); + return result.replaceFirst(options.cutFromModelNames, '').replaceAll('\$\$', '\$'); } String generateEnumName(String className, String enumName) { return getValidatedClassName('${className.capitalize}_$enumName'); } - String generateRequestEnumName( - String path, String requestType, String parameterName) { + String generateRequestEnumName(String path, String requestType, String parameterName) { if (path == '/') { path = '\$'; } @@ -92,8 +87,7 @@ abstract class SwaggerGeneratorBase { } } - if (jsonKey.startsWith(RegExp('[0-9]')) || - exceptionWords.contains(jsonKey)) { + if (jsonKey.startsWith(RegExp('[0-9]')) || exceptionWords.contains(jsonKey)) { jsonKey = '\$$jsonKey'; } @@ -111,16 +105,14 @@ abstract class SwaggerGeneratorBase { swaggerRoot.paths.forEach((String path, SwaggerPath swaggerPath) { swaggerPath.requests.forEach((String req, SwaggerRequest swaggerRequest) { swaggerRequest.parameters = swaggerRequest.parameters - .map((SwaggerRequestParameter parameter) => - getOriginalOrOverriddenRequestParameter(parameter, - swaggerRoot.components?.parameters.values.toList() ?? [])) + .map((SwaggerRequestParameter parameter) => getOriginalOrOverriddenRequestParameter( + parameter, swaggerRoot.components?.parameters.values.toList() ?? [])) .toList(); }); }); swaggerRoot.paths.forEach((String path, SwaggerPath swaggerPath) { - swaggerPath.requests - .forEach((String requestType, SwaggerRequest swaggerRequest) { + swaggerPath.requests.forEach((String requestType, SwaggerRequest swaggerRequest) { if (swaggerRequest.parameters.isEmpty) { return; } @@ -128,8 +120,7 @@ abstract class SwaggerGeneratorBase { for (var p = 0; p < swaggerRequest.parameters.length; p++) { final swaggerRequestParameter = swaggerRequest.parameters[p]; - var name = generateRequestEnumName( - path, requestType, swaggerRequestParameter.name); + var name = generateRequestEnumName(path, requestType, swaggerRequestParameter.name); if (enums.any((element) => element.name == name)) { continue; diff --git a/lib/src/code_generators/swagger_models_generator.dart b/lib/src/code_generators/swagger_models_generator.dart index 5620913d..bac49e3a 100644 --- a/lib/src/code_generators/swagger_models_generator.dart +++ b/lib/src/code_generators/swagger_models_generator.dart @@ -4,6 +4,7 @@ import 'package:swagger_dart_code_generator/src/code_generators/constants.dart'; import 'package:swagger_dart_code_generator/src/code_generators/enum_model.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_generator_base.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_requests_generator.dart'; +import 'package:swagger_dart_code_generator/src/code_generators/utils.dart'; import 'package:swagger_dart_code_generator/src/exception_words.dart'; import 'package:swagger_dart_code_generator/src/extensions/string_extension.dart'; import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; @@ -83,8 +84,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { if (items.hasRef) { final ref = items.ref; - final itemSchema = - allClasses[getValidatedClassName(ref.getUnformattedRef())]; + final itemSchema = allClasses[getValidatedClassName(ref.getUnformattedRef())]; if (itemSchema != null && kBasicTypes.contains(itemSchema.type)) { return 'typedef $className = List<${kBasicTypesMap[itemSchema.type]}>;'; @@ -165,8 +165,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { } } - final shouldUseItemsProperties = - schema.items?.properties.isNotEmpty == true; + final shouldUseItemsProperties = schema.items?.properties.isNotEmpty == true; properties.forEach((propertyKey, propSchema) { final itemPart = shouldUseItemsProperties ? '\$Item\$' : '\$'; @@ -212,22 +211,19 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { } if (options.excludePaths.isNotEmpty && - options.excludePaths - .any((exclPath) => RegExp(exclPath).hasMatch(operation))) { + options.excludePaths.any((exclPath) => RegExp(exclPath).hasMatch(operation))) { return; } if (options.includePaths.isNotEmpty && - !options.includePaths - .any((inclPath) => RegExp(inclPath).hasMatch(operation))) { + !options.includePaths.any((inclPath) => RegExp(inclPath).hasMatch(operation))) { return; } final responses = request.responses; final neededResponse = responses['200'] ?? responses['201']; - final neededSchema = - neededResponse?.schema ?? neededResponse?.content?.schema; + final neededSchema = neededResponse?.schema ?? neededResponse?.content?.schema; if (neededSchema != null && neededSchema.type == kObject && @@ -255,8 +251,8 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { final itemsSchema = neededSchema?.items; if (itemsSchema?.properties.isNotEmpty == true) { - final pathText = key.split('/').map((e) => e.pascalCase).join(); - final requestText = operation.pascalCase; + final pathText = key.split('/').map((e) => e.toClassName).join(); + final requestText = operation.toClassName; results['$pathText$requestText\$Response'] = neededSchema!; } } @@ -275,9 +271,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { }) { final converters = generateJsonConverters(); final allEnumsString = generateEnumsMethods - ? allEnums - .map((e) => e.generateFromJsonToJson(options.enumsCaseSensitive)) - .join() + ? allEnums.map((e) => e.generateFromJsonToJson(options.enumsCaseSensitive)).join() : ''; final allEnumListNames = getAllListEnumNames(root); @@ -302,7 +296,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { return generateModelClassContent( root, - className.pascalCase, + className.toClassName, currentClass, classes, options.defaultValuesMap, @@ -339,8 +333,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { final result = words .map((e) => e .split(RegExp(r'\W+|\_')) - .mapIndexed( - (int index, String str) => index == 0 ? str : str.capitalize) + .mapIndexed((int index, String str) => index == 0 ? str : str.capitalize) .join()) .join('\$'); @@ -348,8 +341,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { return 'enums.$result'; } - if (exceptionWords.contains(result.camelCase) || - kBasicTypes.contains(result.camelCase)) { + if (exceptionWords.contains(result.camelCase) || kBasicTypes.contains(result.camelCase)) { return '\$$result'; } @@ -368,7 +360,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { String? refNameParameter, ) { if (refNameParameter != null) { - return refNameParameter.pascalCase; + return refNameParameter.toClassName; } if (parameter == null) return 'Object'; @@ -385,7 +377,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { } if (parameter.hasRef) { - return parameter.ref.split('/').last.pascalCase; + return parameter.ref.split('/').last.toClassName; } switch (parameter.type) { @@ -414,8 +406,7 @@ abstract class SwaggerModelsGenerator extends SwaggerGeneratorBase { return 'Object'; case 'array': final items = parameter.items; - final typeName = getParameterTypeName( - className, parameterName, items, modelPostfix, null); + final typeName = getParameterTypeName(className, parameterName, items, modelPostfix, null); return 'List<$typeName>'; default: return 'Object'; @@ -516,13 +507,11 @@ class $className implements json.JsonConverter<${value.type}, String> { typeName = typeName.makeNullable(); } - if (requiredProperties.isNotEmpty && - !requiredProperties.contains(propertyKey)) { + if (requiredProperties.isNotEmpty && !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } - if (requiredProperties.isNotEmpty && - !requiredProperties.contains(propertyKey)) { + if (requiredProperties.isNotEmpty && !requiredProperties.contains(propertyKey)) { typeName = typeName.makeNullable(); } @@ -551,10 +540,9 @@ class $className implements json.JsonConverter<${value.type}, String> { isList = isList || allEnumListNames.contains(validatedTypeName); final enumNameCamelCase = typeName.replaceAll('enums.', '').camelCase; - final propertyNameCamelCase = propertyName.pascalCase; - final fromJsonPrefix = defaultValue == null - ? enumNameCamelCase - : '$enumNameCamelCase$propertyNameCamelCase'; + final propertyNameCamelCase = propertyName.toClassName; + final fromJsonPrefix = + defaultValue == null ? enumNameCamelCase : '$enumNameCamelCase$propertyNameCamelCase'; final String fromJsonSuffix; final String toJsonSuffix; @@ -565,10 +553,9 @@ class $className implements json.JsonConverter<${value.type}, String> { } if (isList) { - fromJsonSuffix = - options.classesWithNullabeLists.contains(className) && isList - ? 'NullableListFromJson' - : 'ListFromJson'; + fromJsonSuffix = options.classesWithNullabeLists.contains(className) && isList + ? 'NullableListFromJson' + : 'ListFromJson'; toJsonSuffix = 'ListToJson'; } else { fromJsonSuffix = isNullable ? 'NullableFromJson' : 'FromJson'; @@ -585,9 +572,8 @@ class $className implements json.JsonConverter<${value.type}, String> { if (isList && defaultValue is List) { valueType = 'List'; returnType = 'List<$validatedTypeName>'; - final defaultValues = defaultValue - .map((e) => '$validatedTypeName.${e.toString().camelCase}') - .join(', '); + final defaultValues = + defaultValue.map((e) => '$validatedTypeName.${e.toString().camelCase}').join(', '); defaultValueString = '[$defaultValues]'; } else { valueType = 'Object'; @@ -603,8 +589,7 @@ class $className implements json.JsonConverter<${value.type}, String> { '$validatedTypeName.${defaultValueCamelCase.substring(0, defaultValueCamelCase.indexOf('('))}'; } - if ((options.classesWithNullabeLists.contains(className) && isList) || - isNullable) { + if ((options.classesWithNullabeLists.contains(className) && isList) || isNullable) { returnType = '$returnType?'; } @@ -679,8 +664,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr if (basicTypesMap.containsKey(parameterName)) { typeName = basicTypesMap[parameterName]!; } else { - typeName = getValidatedClassName(getParameterTypeName( - className, propertyName, prop, options.modelPostfix, parameterName)); + typeName = getValidatedClassName( + getParameterTypeName(className, propertyName, prop, options.modelPostfix, parameterName)); } final includeIfNullString = generateIncludeIfNullString(); @@ -708,12 +693,10 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey}$dateToJsonValue)\n"; - final deprecatedContent = - propertySchema.deprecated ? kDeprecatedAnnotation : ''; + final deprecatedContent = propertySchema.deprecated ? kDeprecatedAnnotation : ''; if (prop.shouldBeNullable || - (options.nullableModels.contains(className) && - !requiredProperties.contains(propertyKey))) { + (options.nullableModels.contains(className) && !requiredProperties.contains(propertyKey))) { typeName = typeName.makeNullable(); } @@ -737,10 +720,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final allOf = prop.allOf; String typeName; - if (allOf - .where((element) => - element.ref.isNotEmpty || element.properties.isNotEmpty) - .length > + if (allOf.where((element) => element.ref.isNotEmpty || element.properties.isNotEmpty).length > 1) { typeName = kDynamic; } else if (allOf.first.ref.isNotEmpty) { @@ -751,8 +731,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr } typeName = getValidatedClassName(className); - } else if (allOf.first.type.isNotEmpty && - kBasicTypesMap.containsKey(allOf.first.type)) { + } else if (allOf.first.type.isNotEmpty && kBasicTypesMap.containsKey(allOf.first.type)) { typeName = kBasicTypesMap[allOf.first.type]!; } else { typeName = kDynamic; @@ -814,16 +793,15 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr } else if (basicTypesMap.containsKey(parameterName)) { typeName = basicTypesMap[parameterName]!; } else { - typeName = getValidatedClassName(getParameterTypeName( - className, propertyName, prop, options.modelPostfix, parameterName)); + typeName = getValidatedClassName( + getParameterTypeName(className, propertyName, prop, options.modelPostfix, parameterName)); typeName = getValidatedClassName(typeName); } if (allEnumNames.contains(typeName)) { typeName = 'enums.$typeName'; - } else if (!basicTypesMap.containsKey(parameterName) && - !allEnumListNames.contains(typeName)) { + } else if (!basicTypesMap.containsKey(parameterName) && !allEnumListNames.contains(typeName)) { typeName += options.modelPostfix; } @@ -852,8 +830,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr final jsonKeyContent = "@JsonKey(name: '${_validatePropertyKey(propertyKey)}'$includeIfNullString${unknownEnumValue.jsonKey})\n"; - final deprecatedContent = - refSchema?.deprecated == true ? kDeprecatedAnnotation : ''; + final deprecatedContent = refSchema?.deprecated == true ? kDeprecatedAnnotation : ''; if (prop.shouldBeNullable || options.nullableModels.contains(className) || @@ -929,7 +906,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr required Map allClasses, }) { if (className.endsWith('\$Item')) { - return kObject.pascalCase; + return kObject.toClassName; } final items = prop.items; @@ -938,8 +915,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr if (items != null) { typeName = getValidatedClassName(items.originalRef); - if (typeName.isNotEmpty && - !kBasicTypes.contains(typeName.toLowerCase())) { + if (typeName.isNotEmpty && !kBasicTypes.contains(typeName.toLowerCase())) { typeName += options.modelPostfix; } @@ -957,7 +933,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr if (basicTypesMap.containsKey(typeName)) { typeName = basicTypesMap[typeName]!; } else if (typeName.isNotEmpty && typeName != kDynamic) { - typeName = typeName.pascalCase; + typeName = typeName.toClassName; } } else if (!allEnumNames.contains(typeName) && !kBasicTypes.contains(typeName.toLowerCase())) { @@ -1017,7 +993,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr required Map allClasses, required bool isDeprecated, }) { - final jsonConverterAnnotation = prop.items == null ? '' : generatePropertyJsonConverterAnnotation(prop.items!); + final jsonConverterAnnotation = + prop.items == null ? '' : generatePropertyJsonConverterAnnotation(prop.items!); final typeName = _generateListPropertyTypeName( allEnumListNames: allEnumListNames, allEnumNames: allEnumNames, @@ -1044,10 +1021,8 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr String jsonKeyContent; if (unknownEnumValue.jsonKey.isEmpty) { - if (options.classesWithNullabeLists - .any((element) => RegExp(element).hasMatch(className))) { - jsonKeyContent = - "@JsonKey(name: '$validatedPropertyKey'$includeIfNullString)\n"; + if (options.classesWithNullabeLists.any((element) => RegExp(element).hasMatch(className))) { + jsonKeyContent = "@JsonKey(name: '$validatedPropertyKey'$includeIfNullString)\n"; } else { jsonKeyContent = "@JsonKey(name: '$validatedPropertyKey'$includeIfNullString, defaultValue: <$typeName>[])\n"; @@ -1094,7 +1069,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr if (prop.hasAdditionalProperties && prop.type == 'object') { typeName = kMapStringDynamic; } else if (prop.hasRef) { - typeName = prop.ref.split('/').last.pascalCase + options.modelPostfix; + typeName = prop.ref.split('/').last.toClassName + options.modelPostfix; } else { typeName = getParameterTypeName( className, @@ -1125,15 +1100,12 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr jsonKeyContent += unknownEnumValue.jsonKey; jsonKeyContent += dateToJsonValue; - if ((prop.type == 'bool' || prop.type == 'boolean') && - prop.defaultValue != null) { + if ((prop.type == 'bool' || prop.type == 'boolean') && prop.defaultValue != null) { jsonKeyContent += ', defaultValue: ${prop.defaultValue})\n'; - } else if (defaultValues - .any((DefaultValueMap element) => element.typeName == typeName)) { - final defaultValue = defaultValues.firstWhere( - (DefaultValueMap element) => element.typeName == typeName); - jsonKeyContent += - ', defaultValue: ${generateDefaultValueFromMap(defaultValue)})\n'; + } else if (defaultValues.any((DefaultValueMap element) => element.typeName == typeName)) { + final defaultValue = + defaultValues.firstWhere((DefaultValueMap element) => element.typeName == typeName); + jsonKeyContent += ', defaultValue: ${generateDefaultValueFromMap(defaultValue)})\n'; } else { jsonKeyContent += ')\n'; } @@ -1403,8 +1375,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr entityMap.forEach((key, value) { var fieldName = generateFieldName( - getParameterName( - getValidatedParameterName(key).asParameterName(), propertyNames), + getParameterName(getValidatedParameterName(key).asParameterName(), propertyNames), ); propertyNames.add(fieldName); @@ -1413,8 +1384,7 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr value.shouldBeNullable || !requiredProperties.contains(key); - final isRequiredProperty = - !value.shouldBeNullable && requiredProperties.contains(key); + final isRequiredProperty = !value.shouldBeNullable && requiredProperties.contains(key); if (isRequiredProperty || !isNullableProperty) { results += '\t\t$kRequired this.$fieldName,\n'; @@ -1463,11 +1433,9 @@ static $returnType $fromJsonFunction($valueType? value) => $enumNameCamelCase$fr allClasses, ); - final validatedClassName = - '${getValidatedClassName(className)}${options.modelPostfix}'; + final validatedClassName = '${getValidatedClassName(className)}${options.modelPostfix}'; - final copyWithMethod = - generateCopyWithContent(generatedProperties, validatedClassName); + final copyWithMethod = generateCopyWithContent(generatedProperties, validatedClassName); final getHashContent = generateGetHashContent( generatedProperties, @@ -1540,8 +1508,7 @@ $copyWithMethod return ', createToJson: false'; } - List _getRequired( - SwaggerSchema schema, Map schemas, + List _getRequired(SwaggerSchema schema, Map schemas, [int recursionCount = 5]) { final required = {}; if (recursionCount == 0) { @@ -1549,12 +1516,11 @@ $copyWithMethod } for (var interface in _getInterfaces(schema)) { if (interface.hasRef) { - final parentName = interface.ref.split('/').last.pascalCase; + final parentName = interface.ref.split('/').last.toClassName; final parentSchema = schemas[parentName]; - required.addAll(parentSchema != null - ? _getRequired(parentSchema, schemas, recursionCount - 1) - : []); + required.addAll( + parentSchema != null ? _getRequired(parentSchema, schemas, recursionCount - 1) : []); } required.addAll(interface.required); } @@ -1605,8 +1571,7 @@ $copyWithMethod '''; } - String generateCopyWithContent( - String generatedProperties, String validatedClassName) { + String generateCopyWithContent(String generatedProperties, String validatedClassName) { final splittedCopyWithProperties = RegExp( 'final (.+) (.+);', ).allMatches(generatedProperties).map((e) { @@ -1627,22 +1592,19 @@ $copyWithMethod return ''; } - final spittedCopyWithPropertiesJoined = - splittedCopyWithProperties.join(', '); + final spittedCopyWithPropertiesJoined = splittedCopyWithProperties.join(', '); - final spittedCopyWithWrappedPropertiesJoined = - splittedCopyWithWrappedProperties.join(', '); + final spittedCopyWithWrappedPropertiesJoined = splittedCopyWithWrappedProperties.join(', '); final splittedCopyWithPropertiesNamesContent = splittedCopyWithProperties .map((e) => e.substring(e.indexOf(' ') + 1)) .map((e) => '$e: $e ?? this.$e') .join(',\n'); - final splittedCopyWithWrappedPropertiesNamesContent = - splittedCopyWithWrappedProperties - .map((e) => e.substring(e.indexOf(' ') + 1)) - .map((e) => '$e: ($e != null ? $e.value : this.$e)') - .join(',\n'); + final splittedCopyWithWrappedPropertiesNamesContent = splittedCopyWithWrappedProperties + .map((e) => e.substring(e.indexOf(' ') + 1)) + .map((e) => '$e: ($e != null ? $e.value : this.$e)') + .join(',\n'); final copyWith = '$validatedClassName copyWith({$spittedCopyWithPropertiesJoined}) { return $validatedClassName($splittedCopyWithPropertiesNamesContent); }'; @@ -1669,8 +1631,7 @@ $copyWithMethod .map((e) => e.group(1)!) .map((e) => 'const DeepCollectionEquality().hash($e)'); - final allHashComponents = - [...propertiesHash, 'runtimeType.hashCode'].join(' ^\n'); + final allHashComponents = [...propertiesHash, 'runtimeType.hashCode'].join(' ^\n'); return ''' @override @@ -1692,8 +1653,7 @@ $allHashComponents; final newModelMap = allOf.firstWhereOrNull((m) => m.properties.isNotEmpty); - final currentProperties = - Map.from(schema.properties); + final currentProperties = Map.from(schema.properties); currentProperties.addAll(newModelMap?.properties ?? {}); @@ -1723,8 +1683,7 @@ $allHashComponents; if (schema != null) { if (schema.allOf.isNotEmpty) { - final refs = - allOf.where((element) => element.ref.isNotEmpty).toList(); + final refs = allOf.where((element) => element.ref.isNotEmpty).toList(); for (var allOf in refs) { final allOfSchema = allClasses[allOf.ref.getUnformattedRef()]; @@ -1735,8 +1694,7 @@ $allHashComponents; currentProperties.addAll(allOf.properties); if (allOf.ref.isNotEmpty) { - final oneMoreModel = - allClasses[allOf.ref.getUnformattedRef()]; + final oneMoreModel = allClasses[allOf.ref.getUnformattedRef()]; currentProperties.addAll(oneMoreModel?.properties ?? {}); } } @@ -1773,7 +1731,7 @@ $allHashComponents; final schema = content.schema; if (schema != null) { if (schema.type == kObject && schema.properties.isNotEmpty) { - final className = '${pathKey.pascalCase}${requestKey.pascalCase}'; + final className = '${pathKey.toClassName}${requestKey.toClassName}'; result[getValidatedClassName(className)] = schema; } diff --git a/lib/src/code_generators/swagger_requests_generator.dart b/lib/src/code_generators/swagger_requests_generator.dart index 38d429da..dd43b4ec 100644 --- a/lib/src/code_generators/swagger_requests_generator.dart +++ b/lib/src/code_generators/swagger_requests_generator.dart @@ -4,6 +4,7 @@ import 'package:recase/recase.dart'; import 'package:swagger_dart_code_generator/src/code_generators/enum_model.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_generator_base.dart'; import 'package:swagger_dart_code_generator/src/code_generators/swagger_models_generator.dart'; +import 'package:swagger_dart_code_generator/src/code_generators/utils.dart'; import 'package:swagger_dart_code_generator/src/extensions/parameter_extensions.dart'; import 'package:swagger_dart_code_generator/src/extensions/string_extension.dart'; import 'package:swagger_dart_code_generator/src/models/generator_options.dart'; @@ -502,7 +503,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { }) { return [ if (isDeprecated) refer('deprecated'), - refer(requestType.pascalCase).call( + refer(requestType.toClassName).call( [], { kPath: literalString(path), @@ -516,7 +517,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { refer(kFactoryConverter.pascalCase).call( [], {'request': refer('FormUrlEncodedConverter.requestFactory')}), if (isMultipart) - refer(kMultipart.pascalCase).call( + refer(kMultipart.toClassName).call( [], {}, ), @@ -568,10 +569,10 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return refer(kField) .call([literalString(parameter.name.replaceAll('\$', ''))]); case kBody: - return refer(kBody.pascalCase).call([]); + return refer(kBody.toClassName).call([]); default: //https://github.com/lejard-h/chopper/issues/295 - return refer(parameter.inParameter.pascalCase) + return refer(parameter.inParameter.toClassName) .call([literalString(parameter.name.replaceAll('\$', ''))]); } } @@ -583,11 +584,11 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { }) { final pathString = path .split('/') - .map((e) => e.replaceAll('}', '').replaceAll('{', '').pascalCase) + .map((e) => e.replaceAll('}', '').replaceAll('{', '').toClassName) .join(); final result = getValidatedClassName( - '$pathString ${requestType.pascalCase} $parameterName'); + '$pathString ${requestType.toClassName} $parameterName'); return result.asEnum(); } @@ -720,7 +721,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return _mapParameterName(parameter.schema!.type, format, modelPostfix); } - return kObject.pascalCase; + return kObject.toClassName; } String _mapParameterName(String name, String format, String modelPostfix) { @@ -829,7 +830,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { requestBody.content!.schema!.ref.getRef())) ..named = true ..annotations.add( - refer(kPart.pascalCase).call([]), + refer(kPart.toClassName).call([]), ), ), ); @@ -850,7 +851,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ) ..named = true ..annotations.add( - refer(kPartFile.pascalCase).call([]), + refer(kPartFile.toClassName).call([]), ), ), ); @@ -881,7 +882,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ..required = isRequired ..type = Reference(typeRef) ..annotations.add( - refer(kPartFile.pascalCase).call([]), + refer(kPartFile.toClassName).call([]), ), ), ); @@ -898,7 +899,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ..type = Reference(typeName.makeNullable()) ..named = true ..annotations.add( - refer(kPart.pascalCase).call([literalString(key)]), + refer(kPart.toClassName).call([literalString(key)]), ), ), ); @@ -926,7 +927,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ..type = Reference(options.urlencodedFileType) ..named = true ..annotations.add( - refer(kBody.pascalCase).call([]), + refer(kBody.toClassName).call([]), ), ), ); @@ -966,7 +967,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { final oneOfRef = schema.oneOf.first.ref.getUnformattedRef(); typeName = getValidatedClassName(oneOfRef); } else if (schema.format == kBinary || schema.oneOf.isNotEmpty) { - typeName = kObject.pascalCase; + typeName = kObject.toClassName; } else if (schema.items?.type.isNotEmpty == true) { typeName = _mapParameterName(schema.items!.type, schema.items!.format, options.modelPostfix) @@ -979,7 +980,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { schema: schema, modelPostfix: options.modelPostfix, root: root, - requestPath: path + requestType.pascalCase, + requestPath: path + requestType.toClassName, ); } } @@ -991,12 +992,12 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { ..named = true ..required = true ..type = Reference( - (typeName.isNotEmpty ? typeName : kObject.pascalCase) + (typeName.isNotEmpty ? typeName : kObject.toClassName) .makeNullable(), ) ..named = true ..annotations.add( - refer(kBody.pascalCase).call([]), + refer(kBody.toClassName).call([]), ), ), ); @@ -1053,7 +1054,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { } if (_isBasicTypeRef(ref, root)) { - return kObject.pascalCase; + return kObject.toClassName; } if (ref.isNotEmpty) { @@ -1066,7 +1067,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return getValidatedClassName('$requestPath\$$kRequestBody'); } - return kObject.pascalCase; + return kObject.toClassName; } return kBasicTypesMap[schema.type] ?? schema.type; @@ -1078,7 +1079,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { } if (_isBasicTypeRef(schema.ref, root)) { - return kObject.pascalCase; + return kObject.toClassName; } return getValidatedClassName( @@ -1135,7 +1136,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { required String methodName, required String modelPostfix, }) { - return '${methodName.pascalCase}\$$kResponse$modelPostfix'; + return '${methodName.toClassName}\$$kResponse$modelPostfix'; } String? _getReturnTypeFromType( @@ -1180,11 +1181,11 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { final neededResponse = allReusableObjects[ref.getUnformattedRef()]; if (neededResponse == null) { - return kObject.pascalCase; + return kObject.toClassName; } if (neededResponse.ref.isNotEmpty) { - return kObject.pascalCase; + return kObject.toClassName; } if (kBasicTypes.contains(neededResponse.type)) { @@ -1192,7 +1193,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { } if (neededResponse.oneOf.isNotEmpty) { - return kObject.pascalCase; + return kObject.toClassName; } if (ref.contains('/responses/')) { @@ -1259,11 +1260,11 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { final neededSchema = allRefs[schemaRef.getUnformattedRef()]; if (neededSchema == null) { - return kObject.pascalCase; + return kObject.toClassName; } if (kBasicTypes.contains(neededSchema.type)) { - return kObject.pascalCase; + return kObject.toClassName; } var typeName = @@ -1313,7 +1314,7 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { return itemsItemsType.asList().asList(); } else if (content.schema?.items?.properties.isNotEmpty == true) { - final requestText = requestName.pascalCase; + final requestText = requestName.toClassName; final typeName = getValidatedClassName('$requestText\$Response'); @@ -1332,8 +1333,8 @@ class SwaggerRequestsGenerator extends SwaggerGeneratorBase { } if (content.schema?.properties.isNotEmpty == true) { - final pathText = path.split('/').map((e) => e.pascalCase).join(); - final requestText = method.pascalCase; + final pathText = path.split('/').map((e) => e.toClassName).join(); + final requestText = method.toClassName; return getValidatedClassName('$pathText$requestText\$Response'); } diff --git a/lib/src/code_generators/utils.dart b/lib/src/code_generators/utils.dart new file mode 100644 index 00000000..72278cb6 --- /dev/null +++ b/lib/src/code_generators/utils.dart @@ -0,0 +1,18 @@ +import 'package:recase/recase.dart'; + +class SanitizeClassName extends ReCase { + SanitizeClassName(super.text); + + @override + final symbolSet = {' ', '.', '/', '\\'}; + + String get toClassName => _getClassName(); + + String _getClassName() { + return pascalCase.replaceAll("-", "_"); + } +} + +extension StringSanitizeClassName on String { + String get toClassName => SanitizeClassName(this).toClassName; +} \ No newline at end of file