protectName function

(String?, String?) protectName(
  1. String? name, {
  2. String? description,
  3. bool uniqueIfNull = false,
  4. bool isEnum = false,
  5. bool isMethod = false,
})

Protect name from incorrect symbols, keywords, etc.

Implementation

(String? newName, String? description) protectName(
  String? name, {
  String? description,
  bool uniqueIfNull = false,
  bool isEnum = false,
  bool isMethod = false,
}) {
  final (newName, error) = switch (name) {
    null || '' =>
      uniqueIfNull
          ? (
              uniqueName(isEnum: isEnum),
              'Name not received and was auto-generated.',
            )
          : (null, 'Name not received - field will be skipped.'),
    _
        when name.startsWith(r'$') &&
            name.split('').where((e) => e == r'$').length == 1 =>
      (name.substring(1), null),
    _ when !_nameRegExp.hasMatch(name) => () {
      final normalized = name.toCamel;
      if (normalized.isNotEmpty && _nameRegExp.hasMatch(normalized)) {
        return (normalized, null);
      }

      // Try to normalize by removing invalid parts
      final cleaned = _normalizeInvalidName(name);
      if (cleaned.isNotEmpty && _nameRegExp.hasMatch(cleaned)) {
        return (cleaned, 'Normalized from: `$name` to `$cleaned`.');
      }

      // If normalization failed and uniqueIfNull is true, generate a unique name
      if (uniqueIfNull) {
        return (
          uniqueName(isEnum: isEnum),
          'Invalid name `$name` replaced with auto-generated name.',
        );
      }

      return (
        null,
        'Invalid name `$name` could not be normalized - field will be skipped.',
      );
    }(),
    _ when isEnum && reservedFieldNames.contains(name.toCamel) => (
      '$name $_enumConst',
      'The name has been replaced because it contains a keyword. Original name: `$name`.',
    ),
    _ when !isEnum && !isMethod && reservedFieldNames.contains(name.toCamel) => (
      '${name}Field',
      'The name has been replaced because it conflicts with a Dart type. Original name: `$name`.',
    ),
    _ when isMethod && reservedFieldNames.contains(name.toCamel) => (
      '${name}Value',
      'The name has been replaced because it contains a keyword. Original name: `$name`.',
    ),
    _ => (name, null),
  };

  return (
    newName,
    switch ((description, error)) {
      (null, null) => null,
      (null, _) => error,
      (_, null) => description,
      (_, _) => '$description\n$error',
    },
  );
}