readMapOfMap method

Map<String, Map<String, Object>> readMapOfMap(
  1. Iterable<String> pathSegments, {
  2. bool packageRelated = false,
})

Implementation

Map<String, Map<String, Object>> readMapOfMap(
  Iterable<String> pathSegments, {
  bool packageRelated = false,
}) {
  final usedSegments =
      packageRelated ? [_rootKey, ...pathSegments] : pathSegments;

  Object? data = options;

  for (final key in usedSegments) {
    if (data is Map<String, Object?> && data.containsKey(key)) {
      data = data[key];
    } else {
      return {};
    }
  }

  if (data is Iterable<Object>) {
    return Map.unmodifiable(Map<String, Map<String, Object>>.fromEntries(
      data.fold([], (previousValue, element) {
        if (element is String) {
          return [...previousValue, MapEntry(element, <String, Object>{})];
        }

        if (element is Map<String, Object>) {
          final hasSingleKey = element.keys.length == 1;
          final value = element.values.first;

          if (hasSingleKey && value is Map<String, Object> || value is bool) {
            final updatedValue = value is bool
                ? <String, Object>{'enabled': value}
                : value as Map<String, Object>;

            return [
              ...previousValue,
              MapEntry(element.keys.first, updatedValue),
            ];
          }
        }

        return previousValue;
      }),
    )..removeWhere((key, value) =>
        (value['enabled'] is bool && value['enabled'] == false)));
  } else if (data is Map<String, Object>) {
    final rulesNode = data;

    return Map.unmodifiable(Map<String, Map<String, Object>>.fromEntries([
      ...rulesNode.entries
          .where((entry) => entry.value is bool && entry.value as bool)
          .map((entry) => MapEntry(entry.key, {})),
      ...rulesNode.keys.where((key) {
        final node = rulesNode[key];

        return node is Map<String, Object>;
      }).map((key) => MapEntry(key, rulesNode[key] as Map<String, Object>)),
    ]));
  }

  return {};
}