platform/packages/body_parser/lib/src/map_from_uri.dart

45 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.
2021-06-20 12:37:20 +00:00
void buildMapFromUri(Map map, String body) {
var parseArrayRgx = RegExp(r'^(.+)\[\]$');
2021-06-20 12:37:20 +00:00
for (var keyValuePair in body.split('&')) {
if (keyValuePair.contains('=')) {
2016-12-22 18:08:45 +00:00
var equals = keyValuePair.indexOf('=');
2021-06-20 12:37:20 +00:00
var key = Uri.decodeQueryComponent(keyValuePair.substring(0, equals));
var value = Uri.decodeQueryComponent(keyValuePair.substring(equals + 1));
if (parseArrayRgx.hasMatch(key)) {
2021-06-20 12:37:20 +00:00
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]
2021-06-20 12:37:20 +00:00
var keys = key.split('.');
2021-06-20 12:37:20 +00:00
var targetMap = map[keys[0]] != null ? map[keys[0]] as Map? : {};
map[keys[0]] = targetMap;
2021-06-20 12:37:20 +00:00
for (var i = 1; i < keys.length; i++) {
if (i < keys.length - 1) {
2021-06-20 12:37:20 +00:00
targetMap![keys[i]] = targetMap[keys[i]] ?? {};
targetMap = targetMap[keys[i]] as Map?;
} else {
2021-06-20 12:37:20 +00:00
targetMap![keys[i]] = getValue(value);
}
}
2021-06-20 12:37:20 +00:00
} else {
2017-03-07 21:29:18 +00:00
map[key] = getValue(value);
2021-06-20 12:37:20 +00:00
}
} else {
2017-03-07 21:29:18 +00:00
map[Uri.decodeQueryComponent(keyValuePair)] = true;
2021-06-20 12:37:20 +00:00
}
}
2017-03-07 21:29:18 +00:00
}