forked from card-io/card.io-iOS-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCardIOCreditCardNumberFormatter.m
79 lines (67 loc) · 2.45 KB
/
CardIOCreditCardNumberFormatter.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//
// CardIOCreditCardNumberFormatter.m
// See the file "LICENSE.md" for the full license governing this code.
//
#import "CardIOCreditCardNumberFormatter.h"
#import "CardIOCreditCardInfo.h"
#import "CardIOCreditCardNumber.h"
@implementation CardIOCreditCardNumberFormatter
- (BOOL)getObjectValue:(id __autoreleasing *)obj forString:(NSString *)string errorDescription:(NSString **)error {
NSString *numberString = [CardIOCreditCardNumber stringByRemovingNonNumbers:string];
if ([*obj isKindOfClass:[CardIOCreditCardInfo class]]) {
[*obj setCardNumber:numberString];
} else if (obj) {
*obj = numberString;
} else {
*error = @"Unknown object type";
return NO;
}
return YES;
}
- (NSString *)stringForObjectValue:(id)obj {
NSString *inString = nil;
if ([obj isKindOfClass:[CardIOCreditCardInfo class]]) {
inString = [obj cardNumber];
} else if ([obj isKindOfClass:[NSString class]]) {
inString = obj;
} else {
return nil;
}
CardIOCreditCardType cardType = [CardIOCreditCardNumber cardTypeForCardNumber:inString];
NSMutableString *numbersWithSpaces = [inString mutableCopy];
[numbersWithSpaces replaceOccurrencesOfString:@" " withString:@"" options:0 range:NSMakeRange(0, numbersWithSpaces.length)];
NSUInteger correctLength = [CardIOCreditCardNumber numberLengthForCardNumber:numbersWithSpaces];
if (numbersWithSpaces.length > correctLength) {
[numbersWithSpaces deleteCharactersInRange:NSMakeRange(correctLength, numbersWithSpaces.length - correctLength)];
}
switch(cardType) {
case CardIOCreditCardTypeAmex:
// work back to front to make index calculations easier
if (numbersWithSpaces.length > 10) {
[numbersWithSpaces insertString:@" " atIndex:10];
}
if (numbersWithSpaces.length > 4) {
[numbersWithSpaces insertString:@" " atIndex:4];
}
break;
case CardIOCreditCardTypeJCB:
case CardIOCreditCardTypeVisa:
case CardIOCreditCardTypeMastercard:
case CardIOCreditCardTypeDiscover:
// work back to front to make index calculations easier
if (numbersWithSpaces.length > 12) {
[numbersWithSpaces insertString:@" " atIndex:12];
}
if (numbersWithSpaces.length > 8) {
[numbersWithSpaces insertString:@" " atIndex:8];
}
if (numbersWithSpaces.length > 4) {
[numbersWithSpaces insertString:@" " atIndex:4];
}
break;
default:
break;
}
return numbersWithSpaces;
}
@end