platform/lib/src/map_from_uri.dart

44 lines
1.4 KiB
Dart
Raw Normal View History

import 'get_value.dart';
/// Parses a URI-encoded string into real data! **Wow!**
///
/// Whichever map you provide will be automatically populated from the urlencoded body string you provide.
buildMapFromUri(Map map, String body) {
RegExp parseArrayRgx = new RegExp(r'^(.+)\[\]$');
for (String keyValuePair in body.split('&')) {
if (keyValuePair.contains('=')) {
2016-12-22 18:08:45 +00:00
var equals = keyValuePair.indexOf('=');
String key = Uri.decodeQueryComponent(keyValuePair.substring(0, equals));
2017-03-07 21:29:18 +00:00
String value =
Uri.decodeQueryComponent(keyValuePair.substring(equals + 1));
if (parseArrayRgx.hasMatch(key)) {
Match queryMatch = parseArrayRgx.firstMatch(key);
key = queryMatch.group(1);
if (!(map[key] is List)) {
map[key] = [];
}
map[key].add(getValue(value));
} else if (key.contains('.')) {
// i.e. map.foo.bar => [map, foo, bar]
List<String> keys = key.split('.');
Map targetMap = map[keys[0]] ?? {};
map[keys[0]] = targetMap;
for (int i = 1; i < keys.length; i++) {
if (i < keys.length - 1) {
targetMap[keys[i]] = targetMap[keys[i]] ?? {};
2018-08-11 02:08:44 +00:00
targetMap = targetMap[keys[i]] as Map;
} else {
targetMap[keys[i]] = getValue(value);
}
}
2017-03-07 21:29:18 +00:00
} else
map[key] = getValue(value);
} else
map[Uri.decodeQueryComponent(keyValuePair)] = true;
}
2017-03-07 21:29:18 +00:00
}