Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encode arrays for api #107

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 32 additions & 14 deletions TMTumblrSDK/Core/TMSDKFunctions.m
Original file line number Diff line number Diff line change
Expand Up @@ -17,51 +17,69 @@ @implementation TMSDKFunctions

NSString *TMURLEncode(id value) {
NSString *string;

if ([value isKindOfClass:[NSString class]])
string = (NSString *)value;
else
string = [value stringValue];

return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)string, NULL,
CFSTR("!*'();:@&=+$,/?%#[]%"), kCFStringEncodingUTF8));
}

NSDictionary *TMQueryStringToDictionary(NSString *query) {
NSMutableDictionary *mutableParameterDictionary = [[NSMutableDictionary alloc] init];

NSArray *parameters = [query componentsSeparatedByString:@"&"];
NSString *regexStr = @".*\\[[0-9]+\\]$";
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:regexStr options:NSRegularExpressionAnchorsMatchLines error:nil];

NSString *regexKeyStr = @"\\[[0-9]+\\]$";
NSRegularExpression *replaceKeyRegex = [[NSRegularExpression alloc] initWithPattern:regexKeyStr options:NSRegularExpressionAnchorsMatchLines error:nil];

NSArray *parameters = [query componentsSeparatedByString:@"&"];
for (NSString *parameter in parameters) {
NSArray *keyValuePair = [parameter componentsSeparatedByString:@"="];

if (keyValuePair.count == 2) {
NSString *key = TMURLDecode(keyValuePair[0]);
NSString *value = TMURLDecode(keyValuePair[1]);

NSUInteger matches = [regex numberOfMatchesInString:key options:NSMatchingReportProgress range:NSMakeRange(0, key.length)];
BOOL isArray = matches == 1;
if (isArray) {
key = [replaceKeyRegex stringByReplacingMatchesInString:key options:NSMatchingReportProgress range:NSMakeRange(0, key.length) withTemplate:@""];
}

id existingValueForKey = mutableParameterDictionary[key];

if (existingValueForKey) {
if ([existingValueForKey isKindOfClass:[NSMutableArray class]])
if ([existingValueForKey isKindOfClass:[NSMutableArray class]]) {
[(NSMutableArray *)existingValueForKey addObject:value];
else
}
else {
[mutableParameterDictionary setObject:[NSMutableArray arrayWithObjects:existingValueForKey, value, nil]
forKey:key];
} else
}
}
else if (isArray) {
[mutableParameterDictionary setObject:[NSMutableArray arrayWithObject:value] forKey:key];
}
else {
[mutableParameterDictionary setObject:value forKey:key];
}
}
}

return [NSDictionary dictionaryWithDictionary:mutableParameterDictionary];
}

NSString *TMDictionaryToQueryString(NSDictionary *dictionary) {
NSMutableArray *parameters = [NSMutableArray array];

for (NSString *key in [[dictionary allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]) {
TMAddKeyValuePairToQueryStringMutableArray(key, dictionary[key], parameters);
}

return [parameters componentsJoinedByString:@"&"];
}

Expand All @@ -75,9 +93,9 @@ void TMAddKeyValuePairToQueryStringMutableArray(NSString *key, id value, NSMutab
}
}
else if ([value isKindOfClass:[NSArray class]]) {
for (id arrayValue in (NSArray *)value){
TMAddKeyValuePairToQueryStringMutableArray(key, arrayValue, parameters);
}
[value enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
TMAddKeyValuePairToQueryStringMutableArray([NSString stringWithFormat:@"%@[%ld]", key, idx], obj, parameters);
}];
}
else {
[parameters addObject:[NSString stringWithFormat:@"%@=%@", TMURLEncode(key), TMURLEncode(value)]];
Expand Down
35 changes: 33 additions & 2 deletions Tests/TMSDKFunctionsTest.m
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ - (void)testDictionaryToQueryWithRepeatedParameter {
NSString *title = @"Some $$$@#?@#9i==%&&&&title";
NSArray *tags = @[@"adioj ASD $**$*$ a8aA//&&adsijd====", @"lol", @" foo bar baz "];

NSString *result = [NSString stringWithFormat:@"tag=%@&tag=%@&tag=%@&title=%@", TMURLEncode(tags[0]),
NSString *result = [NSString stringWithFormat:@"tag%%5B0%%5D=%@&tag%%5B1%%5D=%@&tag%%5B2%%5D=%@&title=%@", TMURLEncode(tags[0]),
TMURLEncode(tags[1]), TMURLEncode(tags[2]), TMURLEncode(title)];

XCTAssertEqualObjects(TMDictionaryToQueryString(@{ @"title" : title, @"tag" : tags }), result,
Expand All @@ -76,7 +76,7 @@ - (void)testDictionaryToQueryWithNestedDictionary {
},
};

NSString *expected = [NSString stringWithFormat:@"arrayKey=arrayValue1&arrayKey=arrayValue2&%@=innerDictionaryValue1&%@=innerDictionaryValue2&stringKey=value",
NSString *expected = [NSString stringWithFormat:@"arrayKey%%5B0%%5D=arrayValue1&arrayKey%%5B1%%5D=arrayValue2&%@=innerDictionaryValue1&%@=innerDictionaryValue2&stringKey=value",
TMURLEncode(@"dictionaryKey[innerDictionaryKey1]"),
TMURLEncode(@"dictionaryKey[innerDictionaryKey2]")];

Expand All @@ -85,4 +85,35 @@ - (void)testDictionaryToQueryWithNestedDictionary {
XCTAssertEqualObjects(expected, actual);
}

- (void)testAcceptsSquareBrackets {
NSString *validKey = @"[]keyIsValid";
NSString *validValue = @"";
NSString *validKeyTwo = @"key[0]a";
NSDictionary *input = @{ validKey: validValue, validKeyTwo: validValue };

NSString *expectedStr = [NSString stringWithFormat:@"%@=%@&%@=%@", TMURLEncode(validKey), TMURLEncode(validValue), TMURLEncode(validKeyTwo), TMURLEncode(validValue)];
NSString *actualStr = TMDictionaryToQueryString(input);

NSDictionary *expectedDict = TMQueryStringToDictionary(expectedStr);

XCTAssertTrue([expectedStr isEqualToString:actualStr]);
XCTAssertEqualObjects(input, expectedDict);
}

- (void)testKeysAreTheSame {
NSString *key = @"key";

NSString *arrayIn1 = @"1";
NSString *arrayIn2 = @"2";
NSString *arrayIn3 = @"3";

NSDictionary *input = @{ key: @[ arrayIn1, arrayIn2, arrayIn3 ] };

NSString *queryString = TMDictionaryToQueryString(input);
NSDictionary *output = TMQueryStringToDictionary(queryString);

XCTAssertTrue([key isEqualToString:output.allKeys.firstObject]);
XCTAssertEqualObjects(input, output);
}

@end