when function

LivrRule when(
  1. List<Object?> args,
  2. RuleContext context
)

when: validates the value with rules that depend on another field.

  • {when: [reference, condition, rulesIfTrue, rulesIfFalse]}: the condition is true when the referenced value is not empty and passes the condition rules (their output is discarded). rulesIfFalse is optional.
  • {when: [reference, {'card': rules, 'bank': rules}]}: the string form of the referenced value chooses the rules. An empty or unknown referenced value lets only an empty value pass, others are NOT_ALLOWED_VALUE.

The reference is a field of the object, see parseReference. A branch gets the value as it is, empty values too. An empty list of rules [] is a schema error: any is a branch without rules. Arguments after the 4th are ignored.

Implementation

LivrRule when(List<Object?> args, RuleContext context) {
  if (args.length < 2) {
    throw LivrSchemaException(
      'Rule [when] expects a reference and cases, or a reference, a '
      'condition, rules if true and optional rules if false, got '
      '${args.length} argument(s)',
    );
  }

  final reference = parseReference(args[0], 'when');
  if (args.length == 2) return _switch(reference, args[1], context);

  final condition = _compileBranch(args[1], context);
  final rulesIfTrue = _compileBranch(args[2], context);
  final rulesIfFalse = args.length >= 4
      ? _compileBranch(args[3], context)
      : _noRules;

  return (value, allValues) {
    final refValue = reference(allValues);

    // The condition rules see the object of the field, like the branches
    final isTrue =
        !isNoValue(refValue) && !condition(refValue, allValues).isError;
    return (isTrue ? rulesIfTrue : rulesIfFalse)(value, allValues);
  };
}