checkForVariables method

  1. @visibleForTesting
ContentReplacement checkForVariables(
  1. String content,
  2. Variable variable
)

replaces the variable in the content

Implementation

@visibleForTesting
ContentReplacement checkForVariables(
  String content,
  Variable variable,
) {
  var isVariableUsed = false;

  final newContent = content.replaceAllMapped(
    variablePattern(variable),
    (match) {
      final completeMatch = match.group(0) ?? '';

      final braceCount = int.tryParse(match.group(2) ?? '');
      final wrapWithBraces = braceCount != null;

      if (wrapWithBraces && (braceCount < 2 || braceCount > 3)) {
        throw VariableException(
          variable: completeMatch,
          reason: 'Wrap with braces must be 2 or 3, '
              'but was $braceCount',
        );
      }

      final startsWithBracket =
          RegExp(r'^\{+(?![/^#])$').hasMatch(match.group(1) ?? '');
      final isTag = RegExp(r'^\{+[/^#]').hasMatch(match.group(1) ?? '');
      final endsWithBracket = RegExp(r'\}+$').hasMatch(match.group(3) ?? '');

      if (isTag && endsWithBracket) {
        return completeMatch;
      }

      var startDeliminator = '{';
      var endDeliminator = '}';
      var totalBraceCount = braceCount ?? 2;

      var startDeliminatorSection = '';
      var endDeliminatorSection = '';

      if (startsWithBracket || endsWithBracket) {
        startDeliminatorSection = '{{=<< >>=}}';
        endDeliminatorSection = '<<={{ }}=>>';

        startDeliminator = '<';
        endDeliminator = '>';
        totalBraceCount = 2;
      }

      String result;
      var suffix = '';
      final prefixResult = checkForVariables(match.group(1)!, variable);
      final prefix = prefixResult.content;
      if (prefixResult.used.isNotEmpty) {
        isVariableUsed = true;
      }

      final possibleTag = match.group(3);

      final tag = MustacheTag.values.findFrom(possibleTag);

      if (tag == null) {
        if (possibleTag != null) {
          suffix = possibleTag;
        }

        // the `kDefaultBraces` is not used here to allow unescaping
        final startBraces = startDeliminator * totalBraceCount;
        final endBraces = endDeliminator * totalBraceCount;

        result = '$startBraces${variable.name}$endBraces';
      } else {
        // format the variable
        suffix = MustacheTag.values.suffixFrom(possibleTag) ?? '';
        result = tag.wrap(
          variable.name,
          braceCount: braceCount,
          startDeliminator: startDeliminator,
          endDeliminator: endDeliminator,
        );
      }

      isVariableUsed = true;

      return '$startDeliminatorSection'
          '$prefix'
          '$result'
          '$suffix'
          '$endDeliminatorSection';
    },
  );

  return ContentReplacement(
    content: newContent,
    used: {
      if (isVariableUsed) variable.name,
    },
  );
}