parseReference function

FieldReference parseReference(
  1. Object? reference,
  2. String ruleName
)

Parses a reference to another field for a rule builder: 'name', a field of the object, or 'a/b/0', a path down from it through objects and lists, where ~1 stands for / and ~0 for ~. Throws LivrSchemaException for a reference that is not a string, is empty, has an empty segment (a leading or a trailing / too) or a wrong escape.

On a list, a segment is an index only in the form 0 or [1-9][0-9]*. A segment that is missing, or a value on the way that is not an object (or a list for an index), makes the referenced value missing.

Implementation

FieldReference parseReference(Object? reference, String ruleName) {
  if (reference is! String || reference.isEmpty) {
    throw LivrSchemaException(
      'Rule [$ruleName] expects a reference to a field, got [$reference]',
    );
  }

  // The common case: a field of the object
  if (!reference.contains('/') && !reference.contains('~')) {
    return (data) => data[reference];
  }

  final segments = reference.split('/');
  final keys = List<String>.filled(segments.length, '');
  final indexes = List<int>.filled(segments.length, -1);
  for (var i = 0; i < segments.length; i++) {
    final key = _unescapeSegment(segments[i]);
    if (key == null) {
      throw LivrSchemaException(
        'Rule [$ruleName] got a wrong reference [$reference]: an empty '
        'segment or an escape other than ~0 and ~1',
      );
    }
    keys[i] = key;
    indexes[i] = _listIndex(key);
  }

  return (data) {
    Object? value = data;
    for (var i = 0; i < keys.length; i++) {
      if (value is Map<Object?, Object?>) {
        value = value[keys[i]];
      } else if (value is List<Object?>) {
        final index = indexes[i];
        if (index < 0 || index >= value.length) return null;
        value = value[index];
      } else {
        return null;
      }
    }
    return value;
  };
}