previewResponse function

NmResponsePreview previewResponse(
  1. NmResponseRule rule,
  2. String sample,
  3. NmTelecomL10n l10n
)

Preview response.

Implementation

NmResponsePreview previewResponse(NmResponseRule rule, String sample, NmTelecomL10n l10n) {
  try {
    final matcher = rule.matcher;
    final haystack = matcher.caseSensitive ? sample : sample.toLowerCase();
    final needle = matcher.caseSensitive ? matcher.pattern : matcher.pattern.toLowerCase();
    RegExpMatch? regexMatch;
    String? matchedText;

    switch (matcher.mode) {
      case NmResponseMatchMode.contains:
        final index = haystack.indexOf(needle);
        if (index < 0) return const NmResponsePreview(matched: false);
        matchedText = sample.substring(index, index + matcher.pattern.length);
      case NmResponseMatchMode.startsWith:
        if (!haystack.startsWith(needle)) {
          return const NmResponsePreview(matched: false);
        }
        matchedText = sample.substring(0, matcher.pattern.length);
      case NmResponseMatchMode.regularExpression:
        final expression = RegExp(matcher.pattern, caseSensitive: matcher.caseSensitive);
        regexMatch = expression.firstMatch(sample);
        if (regexMatch == null) return const NmResponsePreview(matched: false);
        matchedText = regexMatch.group(0);
    }

    final values = <NmResponseField, String>{};
    for (final effect in rule.effects) {
      String? raw;
      switch (effect.source) {
        case NmParameterValueSource.fullMatch:
          raw = matchedText;
        case NmParameterValueSource.fixedValue:
          raw = effect.fixedValue;
        case NmParameterValueSource.capture:
          if (regexMatch == null) {
            return NmResponsePreview(matched: true, matchedText: matchedText, error: l10n.cmdSetErrCaptureNeedsRegex);
          }
          final capture = effect.captureNameOrIndex!;
          final index = int.tryParse(capture);
          raw = index == null ? regexMatch.namedGroup(capture) : regexMatch.group(index);
      }
      if (raw == null) {
        return NmResponsePreview(matched: true, matchedText: matchedText, error: l10n.cmdSetErrCannotExtractField(effect.field.label(l10n).toLowerCase()));
      }
      var value = raw;
      for (final normalizer in effect.normalizers) {
        value = _normalize(value, normalizer, l10n);
      }
      values[effect.field] = value;
    }
    return NmResponsePreview(matched: true, matchedText: matchedText, values: values, outcome: rule.outcome);
  } on FormatException catch (error) {
    return NmResponsePreview(matched: false, error: error.message);
  } on RangeError {
    return NmResponsePreview(matched: true, error: l10n.cmdSetErrNoCaptureGroup);
  } on ArgumentError {
    return NmResponsePreview(matched: true, error: l10n.cmdSetErrNoNamedGroup);
  }
}