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, null),
    // https://github.com/Carapacik/swagger_parser/issues/262
    _
        when name.startsWith(r'$') &&
            name
                    .split('')
                    .where(
                      (e) => e == r'$',
                    )
                    .length ==
                1 =>
      (
        name.substring(1),
        'Incorrect name has been replaced. Original name: `$name`.',
      ),
    _ when !_nameRegExp.hasMatch(name) => (
        uniqueName(isEnum: isEnum),
        'Incorrect name has been replaced. Original name: `$name`.',
      ),
    _ when dartKeywords.contains(name.toCamel) => (
        '$name ${isEnum ? _enumConst : _valueConst}',
        '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',
    },
  );
}