BTPaymentMethodNonceParser.m 2.0 KB

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