BTPaymentMethodNonceParser.m 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #import "BTPaymentMethodNonce.h"
  2. #import "BTPaymentMethodNonceParser.h"
  3. @interface BTPaymentMethodNonceParser ()
  4. /// Dictionary of JSON parsing blocks keyed by types as strings. The blocks have the following type:
  5. ///
  6. /// `BTPaymentMethodNonce *(^)(NSDictionary *json)`
  7. @property (nonatomic, strong) NSMutableDictionary *JSONParsingBlocks;
  8. @end
  9. @implementation BTPaymentMethodNonceParser
  10. + (instancetype)sharedParser {
  11. static BTPaymentMethodNonceParser *sharedParser;
  12. static dispatch_once_t onceToken;
  13. dispatch_once(&onceToken, ^{
  14. sharedParser = [[BTPaymentMethodNonceParser alloc] init];
  15. });
  16. return sharedParser;
  17. }
  18. - (NSMutableDictionary *)JSONParsingBlocks {
  19. if (!_JSONParsingBlocks) {
  20. _JSONParsingBlocks = [NSMutableDictionary dictionary];
  21. }
  22. return _JSONParsingBlocks;
  23. }
  24. - (BOOL)isTypeAvailable:(NSString *)type {
  25. return self.JSONParsingBlocks[type] != nil;
  26. }
  27. - (NSArray *)allTypes {
  28. return self.JSONParsingBlocks.allKeys;
  29. }
  30. - (void)registerType:(NSString *)type withParsingBlock:(BTPaymentMethodNonce *(^)(BTJSON *))jsonParsingBlock {
  31. if (jsonParsingBlock) {
  32. self.JSONParsingBlocks[type] = [jsonParsingBlock copy];
  33. }
  34. }
  35. - (BTPaymentMethodNonce *)parseJSON:(BTJSON *)json withParsingBlockForType:(NSString *)type {
  36. BTPaymentMethodNonce *(^block)(BTJSON *) = self.JSONParsingBlocks[type];
  37. if (!json) {
  38. return nil;
  39. }
  40. if (block) {
  41. return block(json);
  42. }
  43. // Unregistered types should fall back to parsing basic nonce and description from JSON
  44. if (![json[@"nonce"] isString]) return nil;
  45. return [[BTPaymentMethodNonce alloc] initWithNonce:[json[@"nonce"] asString]
  46. localizedDescription:[json[@"description"] asString]
  47. type:@"Unknown"
  48. isDefault:[json[@"default"] isTrue]];
  49. }
  50. @end