checkForSections method

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

checks the content for sections (sections) and replaces them with the variable's value

Implementation

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

  final setUpSections = content.replaceAllMapped(
    sectionPattern(variable),
    (match) {
      final possibleSection = match.group(1);
      final section = MustacheSection.values.findFrom(possibleSection);

      // if section is found, then replace the content
      if (section == null) {
        return match.group(0)!;
      }

      isVariableUsed = true;

      final formattedSection = section.format(variable.name);

      return '$sectionSetUp$formattedSection';
    },
  );

  // remove the section setup and all pre/post content
  final sectioned = setUpSections.replaceAllMapped(
    sectionSetupPattern,
    (match) {
      return match.group(1)!;
    },
  );

  // remove all extra line breaks before & after the section
  final _ = sectioned.replaceAllMapped(
    RegExp(r'(\n*)({{[#^/][\w-]+}})$(\n*)', multiLine: true),
    (match) {
      var before = '';
      var after = '';

      final beforeMatch = match.group(1);
      if (beforeMatch != null && beforeMatch.isNotEmpty) {
        before = '\n';
      }

      final afterMatch = match.group(3);
      if (afterMatch != null && afterMatch.isNotEmpty) {
        after = '\n';
      }

      isVariableUsed = true;
      return '$before${match.group(2)!}$after';
    },
  );

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