listLength function
list_length: the value must be a list with the given number of
elements: {list_length: 2}, {list_length: [1, 10]} (min and max) or
{list_length: {'min': 1}}. An empty list is a value, not an empty value.
Implementation
LivrRule listLength(List<Object?> args, RuleContext context) {
var min = 0;
var max = -1; // no maximum
final first = args.isEmpty ? null : args[0];
// Arguments after the ones of the form are ignored
if (first is Map<Object?, Object?>) {
if (first.isEmpty) throw _argumentsError(args);
for (final key in first.keys) {
if (key != 'min' && key != 'max') {
throw LivrSchemaException(
'Rule [list_length] got an unknown option [$key]',
);
}
}
if (first.containsKey('min')) min = _length(first['min'], args);
if (first.containsKey('max')) max = _length(first['max'], args);
} else if (args.length == 1) {
min = max = _length(first, args);
} else if (args.length >= 2) {
min = _length(args[0], args);
max = _length(args[1], args);
} else {
throw _argumentsError(args);
}
if (max >= 0 && min > max) {
throw LivrSchemaException(
'Rule [list_length] got min [$min] greater than max [$max]',
);
}
return (value, allValues) {
if (isNoValue(value)) return RuleResult.valid;
if (value is! List) return RuleResult.error('FORMAT_ERROR');
if (value.length < min) return RuleResult.error('TOO_FEW_ITEMS');
if (max >= 0 && value.length > max) {
return RuleResult.error('TOO_MANY_ITEMS');
}
return RuleResult.valid;
};
}