fake method

String fake(
  1. String str
)

Generator method for combining faker methods based on string input

Example:

print(faker.instance.fake('{{name.lastName}}, {{name.firstName}} {{name.suffix}}'));
outputs: "Marks, Dean Sr."

This will interpolate the format string with the value of methods name.lastName, name.firstName, and name.suffix,

Implementation

// ignore: lines_longer_than_80_chars
/// print(faker.instance.fake('{{name.lastName}}, {{name.firstName}} {{name.suffix}}'));
/// outputs: "Marks, Dean Sr."
/// ```
///
/// This will interpolate the format string with the value of methods
// ignore: comment_references
/// [name.lastName], [name.firstName], and [name.suffix],
///
///
String fake(String str) {
  var res = '';

  if (str.isEmpty) return str;

  // find first matching {{ and }}
  final start = str.indexOf('{{');
  final end = str.indexOf('}}');

  // if no {{ and }} is found, we are done
  if (start == -1 || end == -1) return str;

  // extract method name from between the {{ }} that we found
  // for example: {{name.firstName}}
  final token = str.substring(start + 2, end);
  var method = token.replaceAll('}}', '').replaceAll('{{', '');
  // split the method into module and function
  var parts = method.split('.');

  if (_namespace[parts[0]] == null) {
    throw ArgumentError('invalid module: ${parts[0]}');
  }
  if (_namespace[parts[0]]![parts[1]] == null) {
    throw ArgumentError('invalid method: ${parts[1]}');
  }

  // assign the function from the namespace
  final fn = _namespace[parts[0]]![parts[1]]!;
  // ignore: avoid_dynamic_calls
  final result = fn();

  // replace the found tag with the returned fake value
  res = str.replaceAll('{{$token}}', result.toString());

  // return the response recursively until we are done finding all tags
  return fake(res);
}