Updates STYLEGUIDE (#1371)

* Removes elses on new lines

* Removes macro code

* Fixes inlined returns

* Remove extraneous debug logging. Remove a few more macros I found

* STYLEGUIDE cleanup
:
This commit is contained in:
Cameron 2019-09-16 16:44:09 -07:00 committed by GitHub
parent c26fffa372
commit 7412ab16a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
49 changed files with 587 additions and 731 deletions

View File

@ -29,8 +29,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
if (stripeHandled) {
return true
}
else {
} else {
// This was not a stripe url, do whatever url handling your app
// normally does, if any.
}
@ -46,8 +45,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
if (stripeHandled) {
return true
}
else {
} else {
// This was not a stripe url, do whatever url handling your app
// normally does, if any.
}

View File

@ -18,8 +18,7 @@ class CheckoutRowView: UIView {
self.activityIndicator.startAnimating()
self.activityIndicator.alpha = 1
self.detailLabel.alpha = 0
}
else {
} else {
self.activityIndicator.stopAnimating()
self.activityIndicator.alpha = 0
self.detailLabel.alpha = 1

View File

@ -48,8 +48,7 @@ class CheckoutViewController: UIViewController {
self.activityIndicator.startAnimating()
self.activityIndicator.alpha = 1
self.buyButton.alpha = 0
}
else {
} else {
self.activityIndicator.stopAnimating()
self.activityIndicator.alpha = 0
self.buyButton.alpha = 1
@ -262,6 +261,7 @@ extension CheckoutViewController: STPPaymentContextDelegate {
}
}
func paymentContext(_ paymentContext: STPPaymentContext, didCreatePaymentResult paymentResult: STPPaymentResult, completion: @escaping STPPaymentStatusBlock) {
// Create the PaymentIntent on the backend
// To speed this up, create the PaymentIntent earlier in the checkout flow and update it as necessary (e.g. when the cart subtotal updates or when shipping fees and taxes are calculated, instead of re-creating a PaymentIntent for every payment attempt.
MyAPIClient.sharedClient.createPaymentIntent(products: self.products, shippingMethod: paymentContext.selectedShippingMethod) { result in
@ -320,14 +320,12 @@ extension CheckoutViewController: STPPaymentContextDelegate {
self.paymentRow.loading = paymentContext.loading
if let paymentOption = paymentContext.selectedPaymentOption {
self.paymentRow.detail = paymentOption.label
}
else {
} else {
self.paymentRow.detail = "Select Payment"
}
if let shippingMethod = paymentContext.selectedShippingMethod {
self.shippingRow?.detail = shippingMethod.label
}
else {
} else {
self.shippingRow?.detail = "Select address"
}
self.totalRow.detail = self.numberFormatter.string(from: NSNumber(value: Float(self.paymentContext.paymentAmount)/100))!
@ -375,13 +373,11 @@ extension CheckoutViewController: STPPaymentContextDelegate {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
if address.country == nil || address.country == "US" {
completion(.valid, nil, [upsGround, fedEx], fedEx)
}
else if address.country == "AQ" {
} else if address.country == "AQ" {
let error = NSError(domain: "ShippingError", code: 123, userInfo: [NSLocalizedDescriptionKey: "Invalid Shipping Address",
NSLocalizedFailureReasonErrorKey: "We can't ship to this country."])
completion(.invalid, error, nil, nil)
}
else {
} else {
fedEx.amount = 20.99
fedEx.identifier = "fedex_world"
completion(.valid, nil, [upsWorldwide, fedEx], fedEx)

View File

@ -177,13 +177,11 @@ class BrowseViewController: UITableViewController, STPAddCardViewControllerDeleg
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) {
if address.country == nil || address.country == "US" {
completion(.valid, nil, [upsGround, fedEx], fedEx)
}
else if address.country == "AQ" {
} else if address.country == "AQ" {
let error = NSError(domain: "ShippingError", code: 123, userInfo: [NSLocalizedDescriptionKey: "Invalid Shipping Address",
NSLocalizedFailureReasonErrorKey: "We can't ship to this country."])
completion(.invalid, error, nil, nil)
}
else {
} else {
fedEx.amount = 20.99
completion(.valid, nil, [upsWorldwide, fedEx], fedEx)
}

View File

@ -18,26 +18,28 @@
- Avoid single letter variables. Try using `idx` / `jdx` instead of `i` / `j` in for loops.
- Acronyms should be all lowercase as a method prefix (ex:`url` or `urlString`). Otherwise, they should be all caps when occurring elsewhere in the method name, or as a class name (ex: `handleStripeURLCallbackWithURL`, `stripeID` or `STPAPIClient`)
- Acronyms should be all lowercase as a method prefix (ex:`url` or `urlString`). Otherwise, they should be all caps when occurring elsewhere in the method name, or as a class name (ex: `handleStripeURLCallbackWithURL` or `STPAPIClient`)
- Internal or private methods and ivars should begin with an `_`, e.g. `- (void)_doPrivateStuff` and `id _internalVariable`. This is not required for private properties which should not include an underscore (this is to distinguish them from their underlying variable which automatically has an `_` prefix).
### Control Flow
- Place `else if` and `else` on their own lines:
- Place `else if` and `else` on the same line as the preceding closing curly brace:
```objc
if (condition) {
// A
}
else if (condition) {
} else if (condition) {
// B
}
else {
} else {
// C
}
```
- Always wrap conditional bodies with curly braces
- Each return statement should be on a separate line for ease of debugging. i.e. do NOT write `if (condition) return YES;`
- Use ternary operators sparingly and for simple conditions only:
```objc
@ -46,6 +48,8 @@ type = isCard ? @"card" : @"unknown";
type = dictionary[@"type"] ?: @"default";
```
- `switch` statements for enums should contain an entry for each value and avoid using `default`
### Documentation
- Document using the multi-line syntax in all cases with the content aligned with the first asterisk:
@ -153,7 +157,7 @@ static NSString * const STPSDKVersion = @"11.0.0";
- Stick to Xcode default spacing for interfaces, categories, and protocols
- Always define `NS_ASSUME_NON_NULL_BEGIN` / `NS_ASSUME_NON_NULL_END` in headers
- Always define `NS_ASSUME_NON_NULL_BEGIN` / `NS_ASSUME_NON_NULL_END` in headers. `NS_ASSUME_NON_NULL_BEGIN` / `NS_ASSUME_NON_NULL_END` should also be used in implementation (`.m`) files
```objc
NS_ASSUME_NON_NULL_BEGIN
@ -232,7 +236,7 @@ NS_ASSUME_NON_NULL_END
@property (<nonatomic / atomic>, <assign>, <readonly / readwrite>) <type> <name>;
```
- Omit default properties (`assign`, `readwrite`), except for `strong`
- Omit default properties (`assign`, `readwrite`, `strong`)
- Use `copy` for classes with mutable counterparts such as `NSString`, `NSArray`, `NSDictionary`
@ -256,10 +260,14 @@ NS_ASSUME_NON_NULL_END
### Methods
- If a method takes more than three arguments, each argument should be on a separate line.
- See [Coding Guidelines for Cocoa - Naming Methods](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-BCIGIJJF)
### Implementation
- Do not use `#define` to define a block of code -- `#define` code is very difficult to debug
- Use `#pragma mark - <text>` and `#pragma mark <text>` to group methods In large implementation files:
```objc

View File

@ -1812,7 +1812,6 @@
F12829D91D7747E4008B10D6 /* STPBundleLocator.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = STPBundleLocator.m; sourceTree = "<group>"; };
F12C8DBE1D63DE9F00ADA0D7 /* STPPaymentContextAmountModel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = STPPaymentContextAmountModel.h; sourceTree = "<group>"; };
F12C8DBF1D63DE9F00ADA0D7 /* STPPaymentContextAmountModel.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = STPPaymentContextAmountModel.m; sourceTree = "<group>"; };
F132DFE21D51372A002FF5B7 /* STPWeakStrongMacros.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = STPWeakStrongMacros.h; sourceTree = "<group>"; };
F148ABC31D5D334B0014FD92 /* STPLocalizationUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = STPLocalizationUtils.m; sourceTree = "<group>"; };
F148ABE71D5E805A0014FD92 /* en */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = en; path = Localizations/en.lproj/Localizable.strings; sourceTree = "<group>"; };
F148ABEA1D5E80790014FD92 /* zh-Hans */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = "zh-Hans"; path = "Localizations/zh-Hans.lproj/Localizable.strings"; sourceTree = "<group>"; };
@ -2656,7 +2655,6 @@
F1852F921D80B6EC00367C86 /* STPStringUtils.m */,
F15232221EA9303800D65C67 /* STPURLCallbackHandler.h */,
F15232231EA9303800D65C67 /* STPURLCallbackHandler.m */,
F132DFE21D51372A002FF5B7 /* STPWeakStrongMacros.h */,
);
name = Helpers;
sourceTree = "<group>";

View File

@ -26,15 +26,12 @@
if ([obj isKindOfClass:[NSArray class]]) {
// Save array after removing any null values
[result addObject:[(NSArray *)obj stp_arrayByRemovingNulls]];
}
else if ([obj isKindOfClass:[NSDictionary class]]) {
} else if ([obj isKindOfClass:[NSDictionary class]]) {
// Save dictionary after removing any null values
[result addObject:[(NSDictionary *)obj stp_dictionaryByRemovingNulls]];
}
else if ([obj isKindOfClass:[NSNull class]]) {
} else if ([obj isKindOfClass:[NSNull class]]) {
// Skip null value
}
else {
} else {
// Save other value
[result addObject:obj];
}

View File

@ -21,15 +21,12 @@ NS_ASSUME_NONNULL_BEGIN
if ([obj isKindOfClass:[NSArray class]]) {
// Save array after removing any null values
result[key] = [(NSArray *)obj stp_arrayByRemovingNulls];
}
else if ([obj isKindOfClass:[NSDictionary class]]) {
} else if ([obj isKindOfClass:[NSDictionary class]]) {
// Save dictionary after removing any null values
result[key] = [(NSDictionary *)obj stp_dictionaryByRemovingNulls];
}
else if ([obj isKindOfClass:[NSNull class]]) {
} else if ([obj isKindOfClass:[NSNull class]]) {
// Skip null value
}
else {
} else {
// Save other value
result[key] = obj;
}
@ -74,8 +71,7 @@ NS_ASSUME_NONNULL_BEGIN
// boolValue on NSString is true for "Y", "y", "T", "t", or 1-9
if ([string isEqualToString:@"true"] || [string boolValue]) {
return YES;
}
else {
} else {
return NO;
}
}

View File

@ -80,8 +80,7 @@ typedef void (^STPPaymentAuthorizationStatusCallback)(PKPaymentAuthorizationStat
self.onShippingAddressSelection(stpAddress, ^(STPShippingStatus status, NSArray<PKShippingMethod *>* shippingMethods, NSArray<PKPaymentSummaryItem*> *summaryItems) {
if (status == STPShippingStatusInvalid) {
completion(PKPaymentAuthorizationStatusInvalidShippingPostalAddress, shippingMethods, summaryItems);
}
else {
} else {
completion(PKPaymentAuthorizationStatusSuccess, shippingMethods, summaryItems);
}
});
@ -94,11 +93,9 @@ typedef void (^STPPaymentAuthorizationStatusCallback)(PKPaymentAuthorizationStat
- (void)_finish {
if (self.didSucceed) {
self.onFinish(STPPaymentStatusSuccess, nil);
}
else if (self.lastError) {
} else if (self.lastError) {
self.onFinish(STPPaymentStatusError, self.lastError);
}
else {
} else {
self.onFinish(STPPaymentStatusUserCancellation, nil);
}
}

View File

@ -36,8 +36,7 @@
if (token.tokenId == nil
|| error != nil) {
completion(nil, error ?: [NSError stp_genericConnectionError]);
}
else {
} else {
STPSourceParams *params = [STPSourceParams new];
params.type = STPSourceTypeCard;
params.token = token.tokenId;
@ -53,8 +52,7 @@
if (token.tokenId == nil
|| error != nil) {
completion(nil, error ?: [NSError stp_genericConnectionError]);
}
else {
} else {
STPPaymentMethodCardParams *cardParams = [STPPaymentMethodCardParams new];
cardParams.token = token.tokenId;
STPPaymentMethodBillingDetails *billingDetails = [[self class] billingDetailsFromPKPayment:payment];
@ -115,8 +113,7 @@
params[@"address_country"] = stpAddress.country;
return params;
}
else {
} else {
return nil;
}
}

View File

@ -154,8 +154,7 @@ static NSString * const JSONKeyObject = @"object";
if (deserializers.count == 1) {
// Some deserializers don't conform to STPInternalAPIResponseDecodable
deserializerClass = [deserializers.firstObject class];
}
else if (objectString != nil) {
} else if (objectString != nil) {
for (id<STPAPIResponseDecodable> deserializer in deserializers) {
if ([deserializer respondsToSelector:@selector(stripeObject)]
&& [[(id<STPInternalAPIResponseDecodable>)deserializer stripeObject] isEqualToString:objectString]) {

View File

@ -28,7 +28,6 @@
#import "STPPaymentCardTextFieldCell.h"
#import "STPPromise.h"
#import "STPSectionHeaderView.h"
#import "STPWeakStrongMacros.h"
#import "StripeError.h"
#import "UIBarButtonItem+Stripe.h"
#import "UINavigationBar+Stripe_Theme.h"
@ -292,15 +291,13 @@ typedef NS_ENUM(NSUInteger, STPPaymentCardSection) {
[self.apiClient createPaymentMethodWithParams:paymentMethodParams completion:^(STPPaymentMethod * _Nullable paymentMethod, NSError * _Nullable createPaymentMethodError) {
if (createPaymentMethodError) {
[self handleError:createPaymentMethodError];
}
else {
} else {
if ([self.delegate respondsToSelector:@selector(addCardViewController:didCreatePaymentMethod:completion:)]) {
[self.delegate addCardViewController:self didCreatePaymentMethod:paymentMethod completion:^(NSError * _Nullable attachToCustomerError) {
stpDispatchToMainThreadIfNecessary(^{
if (attachToCustomerError) {
[self handleError:attachToCustomerError];
}
else {
} else {
self.loading = NO;
}
});
@ -372,8 +369,7 @@ typedef NS_ENUM(NSUInteger, STPPaymentCardSection) {
if (isAmex) {
newImage = [STPImageLibrary largeCardAmexCVCImage];
animationTransition = UIViewAnimationOptionTransitionCrossDissolve;
}
else {
} else {
newImage = [STPImageLibrary largeCardBackImage];
animationTransition = UIViewAnimationOptionTransitionFlipFromRight;
}
@ -431,8 +427,7 @@ typedef NS_ENUM(NSUInteger, STPPaymentCardSection) {
- (NSInteger)tableView:(__unused UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (section == STPPaymentCardNumberSection) {
return 1;
}
else if (section == STPPaymentCardBillingAddressSection) {
} else if (section == STPPaymentCardBillingAddressSection) {
return self.addressViewModel.addressCells.count;
}
return 0;

View File

@ -144,8 +144,7 @@ STPContactField const STPContactFieldName = @"STPContactFieldName";
- (NSString *)firstName {
if (self.givenName) {
return self.givenName;
}
else {
} else {
NSArray<NSString *>*components = [self.name componentsSeparatedByString:@" "];
return [components firstObject];
}
@ -154,8 +153,7 @@ STPContactField const STPContactFieldName = @"STPContactFieldName";
- (NSString *)lastName {
if (self.familyName) {
return self.familyName;
}
else {
} else {
NSArray<NSString *>*components = [self.name componentsSeparatedByString:@" "];
NSString *firstName = [components firstObject];
NSString *lastName = [self.name stringByReplacingOccurrencesOfString:firstName withString:@""];
@ -384,8 +382,7 @@ STPContactField const STPContactFieldName = @"STPContactFieldName";
NSString *stringIfHasContentsElseNil(NSString *string) {
if (string.length > 0) {
return string;
}
else {
} else {
return nil;
}
}

View File

@ -46,8 +46,7 @@
formTextField.preservesContentsOnPaste = NO;
formTextField.selectionEnabled = NO;
textField = formTextField;
}
else {
} else {
textField = [[STPValidatedTextField alloc] init];
}
textField.delegate = self;
@ -90,8 +89,7 @@
}];
if (countryCode) {
_countryCodes = [@[@"", countryCode] arrayByAddingObjectsFromArray:otherCountryCodes];
}
else {
} else {
_countryCodes = [@[@""] arrayByAddingObjectsFromArray:otherCountryCodes];
}
UIPickerView *pickerView = [UIPickerView new];
@ -131,8 +129,7 @@
self.textField.placeholder = [self placeholderForAddressField:self.type];
if (!self.lastInList) {
self.textField.returnKeyType = UIReturnKeyNext;
}
else {
} else {
self.textField.returnKeyType = UIReturnKeyDefault;
}
switch (self.type) {
@ -179,8 +176,7 @@
if (!self.lastInList) {
self.textField.inputAccessoryView = self.inputAccessoryToolbar;
}
else {
} else {
self.textField.inputAccessoryView = nil;
}
break;
@ -196,8 +192,7 @@
NSInteger index = [self.countryCodes indexOfObject:self.contents];
if (index == NSNotFound) {
self.textField.text = @"";
}
else {
} else {
[self.countryPickerView selectRow:index inComponent:0 animated:NO];
self.textField.text = [self pickerView:self.countryPickerView titleForRow:index forComponent:0];
}
@ -214,8 +209,7 @@
((STPFormTextField *)self.textField).autoFormattingBehavior = behavior;
if (!self.lastInList) {
self.textField.inputAccessoryView = self.inputAccessoryToolbar;
}
else {
} else {
self.textField.inputAccessoryView = nil;
}
break;
@ -259,14 +253,11 @@
+ (NSString *)stateFieldCaptionForCountryCode:(NSString *)countryCode {
if ([countryCode isEqualToString:@"US"]) {
return STPLocalizedString(@"State", @"Caption for State field on address form (only countries that use state , like United States)");
}
else if ([countryCode isEqualToString:@"CA"]) {
} else if ([countryCode isEqualToString:@"CA"]) {
return STPLocalizedString(@"Province", @"Caption for Province field on address form (only countries that use province, like Canada)");
}
else if ([countryCode isEqualToString:@"GB"]) {
} else if ([countryCode isEqualToString:@"GB"]) {
return STPLocalizedString(@"County", @"Caption for County field on address form (only countries that use county, like United Kingdom)");
}
else {
} else {
return STPLocalizedString(@"State / Province / Region", @"Caption for generalized state/province/region field on address form (not tied to a specific country's format)");
}
}

View File

@ -127,8 +127,7 @@
];
[self.delegate addressViewModel:self addedCellAtIndex:0];
[self.delegate addressViewModelDidChange:self];
}
else if (self.containsStateAndPostalFields) {
} else if (self.containsStateAndPostalFields) {
// Add before city
NSUInteger stateFieldIndex = [self.addressCells indexOfObjectPassingTest:^BOOL(STPAddressFieldTableViewCell * _Nonnull obj, NSUInteger __unused idx, BOOL * _Nonnull __unused stop) {
return (obj.type == STPAddressFieldTypeCity);
@ -145,14 +144,12 @@
[self.delegate addressViewModelDidChange:self];
}
}
}
else if (!shouldBeShowingPostalCode && self.showingPostalCodeCell) {
} else if (!shouldBeShowingPostalCode && self.showingPostalCodeCell) {
if (self.isBillingAddress && self.requiredBillingAddressFields == STPBillingAddressFieldsZip) {
self.addressCells = @[];
[self.delegate addressViewModel:self removedCellAtIndex:0];
[self.delegate addressViewModelDidChange:self];
}
else if (self.containsStateAndPostalFields) {
} else if (self.containsStateAndPostalFields) {
NSUInteger zipFieldIndex = [self.addressCells indexOfObjectPassingTest:^BOOL(STPAddressFieldTableViewCell * _Nonnull obj, NSUInteger __unused idx, BOOL * _Nonnull __unused stop) {
return (obj.type == STPAddressFieldTypeZip);
}];
@ -172,8 +169,7 @@
- (BOOL)containsStateAndPostalFields {
if (self.isBillingAddress) {
return self.requiredBillingAddressFields == STPBillingAddressFieldsFull;
}
else {
} else {
return [self.requiredShippingAddressFields containsObject:STPContactFieldPostalAddress];
}
}
@ -208,8 +204,7 @@
for (STPAddressFieldTableViewCell *cell in self.addressCells) {
if (cell.type == STPAddressFieldTypeCity) {
cityCell = cell;
}
else if (cell.type == STPAddressFieldTypeState) {
} else if (cell.type == STPAddressFieldTypeState) {
stateCell = cell;
}
}
@ -219,8 +214,7 @@
// Don't auto fill if either have text already
// Or if neither are non-nil
return;
}
else {
} else {
self.geocodeInProgress = YES;
CLGeocoder *geocoder = [CLGeocoder new];
@ -262,8 +256,7 @@
- (BOOL)isValid {
if (self.isBillingAddress) {
return [self.address containsRequiredFields:self.requiredBillingAddressFields];
}
else {
} else {
return [self.address containsRequiredShippingAddressFields:self.requiredShippingAddressFields];
}
}

View File

@ -169,15 +169,12 @@
NSString *uiUsageLevel = nil;
if ([self.apiUsage containsObject:NSStringFromClass([STPPaymentContext class])]) {
uiUsageLevel = @"full";
}
else if (self.apiUsage.count == 1
} else if (self.apiUsage.count == 1
&& [self.apiUsage containsObject:NSStringFromClass([STPPaymentCardTextField class])]) {
uiUsageLevel = @"card_text_field";
}
else if (self.apiUsage.count > 0) {
} else if (self.apiUsage.count > 0) {
uiUsageLevel = @"partial";
}
else {
} else {
uiUsageLevel = @"none";
}
productUsage[@"ui_usage_level"] = uiUsageLevel;

View File

@ -10,9 +10,22 @@
#import <objc/runtime.h>
#import <objc/message.h>
#define STPAspectLog(...)
//#define STPAspectLog(...) do { NSLog(__VA_ARGS__); }while(0)
#define STPAspectLogError(...) do { NSLog(__VA_ARGS__); }while(0)
NS_INLINE void STPAspectLog(__unused NSString *format, ...) {
// intentionally commented out as a no-op. Can be uncommented for additional debugging
/*
va_list args;
va_start(args, format);
NSLog(format, args);
va_end(args);
*/
}
NS_INLINE void STPAspectLogError(NSString *format, ...) {
va_list args;
va_start(args, format);
NSLog(format, args);
va_end(args);
}
// Block internals.
typedef NS_OPTIONS(int, STPAspectBlockFlags) {
@ -81,11 +94,14 @@ typedef struct _STPAspectBlock {
- (NSArray *)stp_aspects_arguments;
@end
#define STPAspectPositionFilter 0x07
static NSUInteger const STPAspectPositionFilter = 0x07;
#define STPAspectError(errorCode, errorDescription) do { \
STPAspectLogError(@"STPAspects: %@", errorDescription); \
if (error) { *error = [NSError errorWithDomain:STPAspectErrorDomain code:errorCode userInfo:@{NSLocalizedDescriptionKey: errorDescription}]; }}while(0)
NS_INLINE void STPAspectError(STPAspectErrorCode errorCode, NSString *errorDescription, NSError * __autoreleasing *error) {
STPAspectLogError(@"STPAspects: %@", errorDescription);
if (error != nil) {
*error = [NSError errorWithDomain:STPAspectErrorDomain code:errorCode userInfo:@{NSLocalizedDescriptionKey: errorDescription}];
}
}
NSString *const STPAspectErrorDomain = @"STPAspectErrorDomain";
static NSString *const STPAspectsSubclassSuffix = @"_STPAspects_";
@ -152,7 +168,7 @@ static BOOL stp_aspect_remove(STPAspectIdentifier *aspect, NSError * __autorelea
aspect.selector = NULL;
}else {
NSString *errrorDesc = [NSString stringWithFormat:@"Unable to deregister hook. Object already deallocated: %@", aspect];
STPAspectError(STPAspectErrorRemoveObjectAlreadyDeallocated, errrorDesc);
STPAspectError(STPAspectErrorRemoveObjectAlreadyDeallocated, errrorDesc, error);
}
});
return success;
@ -174,7 +190,7 @@ static NSMethodSignature *stp_aspect_blockMethodSignature(id block, NSError **er
STPAspectBlockRef layout = (__bridge void *)block;
if (!(layout->flags & STPAspectBlockFlagsHasSignature)) {
NSString *description = [NSString stringWithFormat:@"The block %@ doesn't contain a type signature.", block];
STPAspectError(STPAspectErrorMissingBlockSignature, description);
STPAspectError(STPAspectErrorMissingBlockSignature, description, error);
return nil;
}
void *desc = layout->descriptor;
@ -184,7 +200,7 @@ static NSMethodSignature *stp_aspect_blockMethodSignature(id block, NSError **er
}
if (!desc) {
NSString *description = [NSString stringWithFormat:@"The block %@ doesn't has a type signature.", block];
STPAspectError(STPAspectErrorMissingBlockSignature, description);
STPAspectError(STPAspectErrorMissingBlockSignature, description, error);
return nil;
}
const char *signature = (*(const char **)desc);
@ -223,7 +239,7 @@ static BOOL stp_aspect_isCompatibleBlockSignature(NSMethodSignature *blockSignat
if (!signaturesMatch) {
NSString *description = [NSString stringWithFormat:@"Block signature %@ doesn't match %@.", blockSignature, methodSignature];
STPAspectError(STPAspectErrorIncompatibleBlockSignature, description);
STPAspectError(STPAspectErrorIncompatibleBlockSignature, description, error);
return NO;
}
return YES;
@ -373,7 +389,7 @@ static Class stp_aspect_hookClass(NSObject *self, NSError **error) {
subclass = objc_allocateClassPair(baseClass, subclassName, 0);
if (subclass == nil) {
NSString *errrorDesc = [NSString stringWithFormat:@"objc_allocateClassPair failed to allocate class %s.", subclassName];
STPAspectError(STPAspectErrorFailedToAllocateClassPair, errrorDesc);
STPAspectError(STPAspectErrorFailedToAllocateClassPair, errrorDesc, error);
return nil;
}
@ -461,13 +477,15 @@ static void stp_aspect_undoSwizzleClassInPlace(Class klass) {
///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Aspect Invoke Point
// This is a macro so we get a cleaner stack trace.
#define stp_aspect_invoke(aspects, info) \
for (STPAspectIdentifier *aspect in aspects) {\
[aspect invokeWithInfo:info];\
if (aspect.options & STPAspectOptionAutomaticRemoval) { \
aspectsToRemove = [aspectsToRemove?:@[] arrayByAddingObject:aspect]; \
} \
NS_INLINE void STPAspectInvoke(NSArray<STPAspectIdentifier *> *aspects, id<STPAspectInfo> info, NSArray **aspectsToRemove) {
for (STPAspectIdentifier *aspect in aspects) {
[aspect invokeWithInfo:info];
if (aspect.options & STPAspectOptionAutomaticRemoval) {
if (aspectsToRemove != nil) {
*aspectsToRemove = [*aspectsToRemove ?: @[] arrayByAddingObject:aspect];
}
}
}
}
// This is the swizzled forwardInvocation: method.
@ -483,14 +501,14 @@ static void __STP_ASPECTS_ARE_BEING_CALLED__(__unsafe_unretained NSObject *self,
NSArray *aspectsToRemove = nil;
// Before hooks.
stp_aspect_invoke(classContainer.beforeAspects, info);
stp_aspect_invoke(objectContainer.beforeAspects, info);
STPAspectInvoke(classContainer.beforeAspects, info, &aspectsToRemove);
STPAspectInvoke(objectContainer.beforeAspects, info, &aspectsToRemove);
// Instead hooks.
BOOL respondsToAlias = YES;
if (objectContainer.insteadAspects.count || classContainer.insteadAspects.count) {
stp_aspect_invoke(classContainer.insteadAspects, info);
stp_aspect_invoke(objectContainer.insteadAspects, info);
STPAspectInvoke(classContainer.insteadAspects, info, &aspectsToRemove);
STPAspectInvoke(objectContainer.insteadAspects, info, &aspectsToRemove);
}else {
Class klass = object_getClass(invocation.target);
do {
@ -502,8 +520,8 @@ static void __STP_ASPECTS_ARE_BEING_CALLED__(__unsafe_unretained NSObject *self,
}
// After hooks.
stp_aspect_invoke(classContainer.afterAspects, info);
stp_aspect_invoke(objectContainer.afterAspects, info);
STPAspectInvoke(classContainer.afterAspects, info, &aspectsToRemove);
STPAspectInvoke(objectContainer.afterAspects, info, &aspectsToRemove);
// If no hooks are installed, call original implementation (usually to throw an exception)
if (!respondsToAlias) {
@ -519,7 +537,6 @@ static void __STP_ASPECTS_ARE_BEING_CALLED__(__unsafe_unretained NSObject *self,
// Remove any hooks that are queued for deregistration.
[aspectsToRemove makeObjectsPerformSelector:@selector(remove)];
}
#undef stp_aspect_invoke
///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Aspect Container Management
@ -576,7 +593,7 @@ static BOOL stp_aspect_isSelectorAllowedAndTrack(NSObject *self, SEL selector, S
NSString *selectorName = NSStringFromSelector(selector);
if ([disallowedSelectorList containsObject:selectorName]) {
NSString *errorDescription = [NSString stringWithFormat:@"Selector %@ is blacklisted.", selectorName];
STPAspectError(STPAspectErrorSelectorBlacklisted, errorDescription);
STPAspectError(STPAspectErrorSelectorBlacklisted, errorDescription, error);
return NO;
}
@ -584,13 +601,13 @@ static BOOL stp_aspect_isSelectorAllowedAndTrack(NSObject *self, SEL selector, S
STPAspectOptions position = options&STPAspectPositionFilter;
if ([selectorName isEqualToString:@"dealloc"] && position != STPAspectPositionBefore) {
NSString *errorDesc = @"AspectPositionBefore is the only valid position when hooking dealloc.";
STPAspectError(STPAspectErrorSelectorDeallocPosition, errorDesc);
STPAspectError(STPAspectErrorSelectorDeallocPosition, errorDesc, error);
return NO;
}
if (![self respondsToSelector:selector] && ![self.class instancesRespondToSelector:selector]) {
NSString *errorDesc = [NSString stringWithFormat:@"Unable to find selector -[%@ %@].", NSStringFromClass(self.class), selectorName];
STPAspectError(STPAspectErrorDoesNotRespondToSelector, errorDesc);
STPAspectError(STPAspectErrorDoesNotRespondToSelector, errorDesc, error);
return NO;
}
@ -605,7 +622,7 @@ static BOOL stp_aspect_isSelectorAllowedAndTrack(NSObject *self, SEL selector, S
NSSet *subclassTracker = [tracker subclassTrackersHookingSelectorName:selectorName];
NSSet *subclassNames = [subclassTracker valueForKey:@"trackedClassName"];
NSString *errorDescription = [NSString stringWithFormat:@"Error: %@ already hooked subclasses: %@. A method can only be hooked once per class hierarchy.", selectorName, subclassNames];
STPAspectError(STPAspectErrorSelectorAlreadyHookedInClassHierarchy, errorDescription);
STPAspectError(STPAspectErrorSelectorAlreadyHookedInClassHierarchy, errorDescription, error);
return NO;
}
@ -617,7 +634,7 @@ static BOOL stp_aspect_isSelectorAllowedAndTrack(NSObject *self, SEL selector, S
return YES;
}
NSString *errorDescription = [NSString stringWithFormat:@"Error: %@ already hooked in %@. A method can only be hooked once per class hierarchy.", selectorName, NSStringFromClass(currentClass)];
STPAspectError(STPAspectErrorSelectorAlreadyHookedInClassHierarchy, errorDescription);
STPAspectError(STPAspectErrorSelectorAlreadyHookedInClassHierarchy, errorDescription, error);
return NO;
}
} while ((currentClass = class_getSuperclass(currentClass)));
@ -648,7 +665,9 @@ static BOOL stp_aspect_isSelectorAllowedAndTrack(NSObject *self, SEL selector, S
}
static void stp_aspect_deregisterTrackedSelector(id self, SEL selector) {
if (!class_isMetaClass(object_getClass(self))) return;
if (!class_isMetaClass(object_getClass(self))) {
return;
}
NSMutableDictionary *swizzledClassesDict = stp_aspect_getSwizzledClassesDict();
NSString *selectorName = NSStringFromSelector(selector);
@ -731,7 +750,6 @@ static void stp_aspect_deregisterTrackedSelector(id self, SEL selector) {
// Skip const type qualifier.
if (argType[0] == _C_CONST) argType++;
#define WRAP_AND_RETURN(type) do { type val = 0; [self getArgument:&val atIndex:(NSInteger)index]; return @(val); } while (0)
if (strcmp(argType, @encode(id)) == 0 || strcmp(argType, @encode(Class)) == 0) {
__autoreleasing id returnObj;
[self getArgument:&returnObj atIndex:(NSInteger)index];
@ -746,35 +764,65 @@ static void stp_aspect_deregisterTrackedSelector(id self, SEL selector) {
return theClass;
// Using this list will box the number with the appropriate constructor, instead of the generic NSValue.
} else if (strcmp(argType, @encode(char)) == 0) {
WRAP_AND_RETURN(char);
char val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(int)) == 0) {
WRAP_AND_RETURN(int);
int val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(short)) == 0) {
WRAP_AND_RETURN(short);
short val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(long)) == 0) {
WRAP_AND_RETURN(long);
long val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(long long)) == 0) {
WRAP_AND_RETURN(long long);
long long val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(unsigned char)) == 0) {
WRAP_AND_RETURN(unsigned char);
unsigned char val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(unsigned int)) == 0) {
WRAP_AND_RETURN(unsigned int);
unsigned int val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(unsigned short)) == 0) {
WRAP_AND_RETURN(unsigned short);
unsigned short val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(unsigned long)) == 0) {
WRAP_AND_RETURN(unsigned long);
unsigned long val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(unsigned long long)) == 0) {
WRAP_AND_RETURN(unsigned long long);
unsigned long long val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(float)) == 0) {
WRAP_AND_RETURN(float);
float val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(double)) == 0) {
WRAP_AND_RETURN(double);
double val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(BOOL)) == 0) {
WRAP_AND_RETURN(BOOL);
BOOL val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(bool)) == 0) {
WRAP_AND_RETURN(BOOL);
BOOL val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(char *)) == 0) {
WRAP_AND_RETURN(const char *);
const char * val = 0;
[self getArgument:&val atIndex:(NSInteger)index];
return @(val);
} else if (strcmp(argType, @encode(void (^)(void))) == 0) {
__unsafe_unretained id block = nil;
[self getArgument:&block atIndex:(NSInteger)index];
@ -789,7 +837,6 @@ static void stp_aspect_deregisterTrackedSelector(id self, SEL selector) {
return [NSValue valueWithBytes:valueBytes objCType:argType];
}
return nil;
#undef WRAP_AND_RETURN
}
- (NSArray *)stp_aspects_arguments {

View File

@ -106,15 +106,13 @@
if (number.length < self.qRangeLow.length) {
withinLowRange = number.integerValue >= [self.qRangeLow substringToIndex:number.length].integerValue;
}
else {
} else {
withinLowRange = [number substringToIndex:self.qRangeLow.length].integerValue >= self.qRangeLow.integerValue;
}
if (number.length < self.qRangeHigh.length) {
withinHighRange = number.integerValue <= [self.qRangeHigh substringToIndex:number.length].integerValue;
}
else {
} else {
withinHighRange = [number substringToIndex:self.qRangeHigh.length].integerValue <= self.qRangeHigh.integerValue;
}

View File

@ -124,11 +124,9 @@ static NSString * _Nonnull stringByRemovingCharactersFromSet(NSString * _Nonnull
NSUInteger maxLength = [self maxCVCLengthForCardBrand:brand];
if (sanitizedCvc.length < minLength) {
return STPCardValidationStateIncomplete;
}
else if (sanitizedCvc.length > maxLength) {
} else if (sanitizedCvc.length > maxLength) {
return STPCardValidationStateInvalid;
}
else {
} else {
return STPCardValidationStateValid;
}
}
@ -178,8 +176,7 @@ static NSString * _Nonnull stringByRemovingCharactersFromSet(NSString * _Nonnull
STPCardValidationState state = [boxedState integerValue];
if (state == STPCardValidationStateInvalid) {
return state;
}
else if (state == STPCardValidationStateIncomplete) {
} else if (state == STPCardValidationStateIncomplete) {
incomplete = YES;
}
}

View File

@ -116,8 +116,7 @@ NS_ASSUME_NONNULL_BEGIN
self.defaultSource = card;
}
}
}
else if ([object isEqualToString:@"source"]) {
} else if ([object isEqualToString:@"source"]) {
STPSource *source = [STPSource decodedObjectFromAPIResponse:contents];
BOOL includeSource = source != nil;
// ignore apple pay cards from the response

View File

@ -15,7 +15,6 @@
#import "STPPaymentMethod.h"
#import "STPPaymentMethodCard.h"
#import "STPPaymentMethodCardWallet.h"
#import "STPWeakStrongMacros.h"
#import "STPDispatchFunctions.h"
static NSTimeInterval const CachedCustomerMaxAge = 60;

View File

@ -11,8 +11,7 @@
void stpDispatchToMainThreadIfNecessary(dispatch_block_t block) {
if ([NSThread isMainThread]) {
block();
}
else {
} else {
dispatch_async(dispatch_get_main_queue(), block);
}
}

View File

@ -13,7 +13,6 @@
#import "STPCardValidator+Private.h"
#import "STPDelegateProxy.h"
#import "STPPhoneNumberValidator.h"
#import "STPWeakStrongMacros.h"
@interface STPTextFieldDelegateProxy : STPDelegateProxy<UITextFieldDelegate>
@property (nonatomic, assign) STPFormTextFieldAutoFormattingBehavior autoformattingBehavior;
@ -53,8 +52,7 @@
if (deleting) {
NSString *sanitized = [self unformattedStringForString:textField.text];
inputText = [sanitized stp_safeSubstringToIndex:sanitized.length - 1];
}
else {
} else {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
// Removes any disallowed characters from the whole string.
// If we (incorrectly) allowed a space to start the text entry hoping it would be a
@ -153,14 +151,14 @@ typedef NSAttributedString* (^STPFormTextTransformationBlock)(NSAttributedString
};
break;
case STPFormTextFieldAutoFormattingBehaviorPhoneNumbers: {
WEAK(self);
__weak typeof(self) weakSelf = self;
self.textFormattingBlock = ^NSAttributedString *(NSAttributedString *inputString) {
if (![STPCardValidator stringIsNumeric:inputString.string]) {
return [inputString copy];
}
STRONG(self);
__strong typeof(self) strongSelf = weakSelf;
NSString *phoneNumber = [STPPhoneNumberValidator formattedSanitizedPhoneNumberForString:inputString.string];
NSDictionary *attributes = [[self class] attributesForAttributedString:inputString];
NSDictionary *attributes = [[strongSelf class] attributesForAttributedString:inputString];
return [[NSAttributedString alloc] initWithString:phoneNumber attributes:attributes];
};
break;

View File

@ -17,7 +17,6 @@
#import "STPImageLibrary.h"
#import "STPPaymentCardTextFieldViewModel.h"
#import "STPPostalCodeValidator.h"
#import "STPWeakStrongMacros.h"
#import "Stripe.h"
#import "STPLocalizationUtils.h"
@ -79,6 +78,15 @@
@end
NS_INLINE CGFloat stp_ceilCGFloat(CGFloat x) {
#if CGFLOAT_IS_DOUBLE
return ceil(x);
#else
return ceilf(x);
#endif
}
@implementation STPPaymentCardTextField
@synthesize font = _font;
@ -94,14 +102,6 @@ CGFloat const STPPaymentCardTextFieldDefaultPadding = 13;
CGFloat const STPPaymentCardTextFieldDefaultInsets = 13;
CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
#if CGFLOAT_IS_DOUBLE
#define stp_roundCGFloat(x) round(x)
#define stp_ceilCGFloat(x) ceil(x)
#else
#define stp_roundCGFloat(x) roundf(x)
#define stp_ceilCGFloat(x) ceilf(x)
#endif
#pragma mark initializers
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
@ -383,8 +383,7 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
if ([countryCode isEqualToString:@"US"]) {
self.postalCodeField.keyboardType = UIKeyboardTypePhonePad;
}
else {
} else {
self.postalCodeField.keyboardType = UIKeyboardTypeDefault;
}
@ -395,8 +394,7 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
- (void)updatePostalFieldPlaceholder {
if (self.postalCodePlaceholder == nil) {
self.postalCodeField.placeholder = [self defaultPostalFieldPlaceholderForCountryCode:self.countryCode];
}
else {
} else {
self.postalCodeField.placeholder = _postalCodePlaceholder;
}
}
@ -404,8 +402,7 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
- (NSString *)defaultPostalFieldPlaceholderForCountryCode:(NSString *)countryCode {
if ([countryCode.uppercaseString isEqualToString:@"US"]) {
return STPLocalizedString(@"ZIP", @"Short string for zip code (United States only)");
}
else {
} else {
return STPLocalizedString(@"Postal", @"Short string for postal code (text used in non-US countries)");
}
}
@ -422,8 +419,7 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
_borderColor = borderColor;
if (borderColor) {
self.layer.borderColor = [[borderColor copy] CGColor];
}
else {
} else {
self.layer.borderColor = [[UIColor clearColor] CGColor];
}
}
@ -523,18 +519,14 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
- (nullable STPFormTextField *)firstInvalidSubField {
if ([self.viewModel validationStateForField:STPCardFieldTypeNumber] != STPCardValidationStateValid) {
return self.numberField;
}
else if ([self.viewModel validationStateForField:STPCardFieldTypeExpiration] != STPCardValidationStateValid) {
} else if ([self.viewModel validationStateForField:STPCardFieldTypeExpiration] != STPCardValidationStateValid) {
return self.expirationField;
}
else if ([self.viewModel validationStateForField:STPCardFieldTypeCVC] != STPCardValidationStateValid) {
} else if ([self.viewModel validationStateForField:STPCardFieldTypeCVC] != STPCardValidationStateValid) {
return self.cvcField;
}
else if (self.postalCodeEntryEnabled
} else if (self.postalCodeEntryEnabled
&& [self.viewModel validationStateForField:STPCardFieldTypePostalCode] != STPCardValidationStateValid) {
return self.postalCodeField;
}
else {
} else {
return nil;
}
}
@ -588,13 +580,13 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
[self onChange];
[self updateImageForFieldType:STPCardFieldTypeNumber];
[self updateCVCPlaceholder];
WEAK(self);
__weak typeof(self) weakSelf = self;
[self layoutViewsToFocusField:@(STPCardFieldTypePostalCode)
animated:YES
completion:^(__unused BOOL completed){
STRONG(self);
if ([self isFirstResponder]) {
[[self numberField] becomeFirstResponder];
__strong typeof(self) strongSelf = weakSelf;
if ([strongSelf isFirstResponder]) {
[[strongSelf numberField] becomeFirstResponder];
}
}];
}
@ -636,8 +628,7 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
- (NSString *)postalCode {
if (self.postalCodeEntryEnabled) {
return self.viewModel.postalCode;
}
else {
} else {
return nil;
}
}
@ -682,8 +673,7 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
(unsigned long)desiredCardParams.expMonth.integerValue,
(unsigned long)desiredCardParams.expYear.integerValue%100];
[self setText:text inField:STPCardFieldTypeExpiration];
}
else {
} else {
[self setText:@"" inField:STPCardFieldTypeExpiration];
}
[self setText:desiredCardParams.cvc inField:STPCardFieldTypeCVC];
@ -696,16 +686,13 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
STPFormTextField *nextField = [self firstInvalidSubField];
if (nextField) {
[nextField becomeFirstResponder];
}
else {
} else {
[self resignFirstResponder];
}
}
else {
} else {
[originalSubResponder becomeFirstResponder];
}
}
else {
} else {
[self layoutViewsToFocusField:nil
animated:NO
completion:nil];
@ -714,11 +701,9 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
// update the card image, falling back to the number field image if not editing
if ([self.expirationField isFirstResponder]) {
[self updateImageForFieldType:STPCardFieldTypeExpiration];
}
else if ([self.cvcField isFirstResponder]) {
} else if ([self.cvcField isFirstResponder]) {
[self updateImageForFieldType:STPCardFieldTypeCVC];
}
else {
} else {
[self updateImageForFieldType:STPCardFieldTypeNumber];
}
[self updateCVCPlaceholder];
@ -748,8 +733,7 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
// Current longest possible pan is 16 digits which our standard sample fits
if ([self.viewModel validationStateForField:STPCardFieldTypeNumber] == STPCardValidationStateValid) {
return [self widthForCardNumber:self.viewModel.cardNumber];
}
else {
} else {
return MAX([self widthForCardNumber:self.viewModel.cardNumber],
[self widthForCardNumber:self.viewModel.defaultPlaceholder]);
}
@ -776,8 +760,7 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
&& [self.viewModel validationStateForField:STPCardFieldTypeCVC] == STPCardValidationStateValid) {
// If we're not focused and have valid text, size exactly to what is entered
return [self widthForText:self.viewModel.cvc];
}
else {
} else {
// Otherwise size to fit our placeholder or what is likely to be the
// largest possible string enterable (whichever is larger)
NSInteger maxCvcLength = [STPCardValidator maxCVCLengthForCardBrand:self.viewModel.brand];
@ -795,8 +778,7 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
&& [self.viewModel validationStateForField:STPCardFieldTypeExpiration] == STPCardValidationStateValid) {
// If we're not focused and have valid text, size exactly to what is entered
return [self widthForText:self.viewModel.rawExpiration];
}
else {
} else {
// Otherwise size to fit our placeholder or what is likely to be the
// largest possible string enterable (whichever is larger)
return MAX([self widthForText:self.expirationField.placeholder], [self widthForText:@"88/88"]);
@ -809,13 +791,11 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
if (currentTextWidth <= compressedWidth) {
return compressedWidth;
}
else if ([self.countryCode.uppercaseString isEqualToString:@"US"]) {
} else if ([self.countryCode.uppercaseString isEqualToString:@"US"]) {
// This format matches ZIP+4 which is currently disabled since it is
// not used for billing, but could be useful for future shipping addr purposes
return [self widthForText:@"88888-8888"];
}
else {
} else {
// This format more closely matches the typical max UK/Canadian size which is our most common non-US market currently
return [self widthForText:@"888 8888"];
}
@ -825,8 +805,7 @@ CGFloat const STPPaymentCardTextFieldMinimumPadding = 10;
CGFloat maxTextWidth = 0;
if ([self.countryCode.uppercaseString isEqualToString:@"US"]) {
maxTextWidth = [self widthForText:@"88888"];
}
else {
} else {
// This format more closely matches the typical max UK/Canadian size which is our most common non-US market currently
maxTextWidth = [self widthForText:@"888 8888"];
}
@ -895,8 +874,7 @@ typedef NS_ENUM(NSInteger, STPCardTextFieldState) {
if (paddingsRequired > 0) {
return stp_ceilCGFloat(((width - requiredWidth) / paddingsRequired));
}
else {
} else {
return STPPaymentCardTextFieldMinimumPadding;
}
}
@ -947,8 +925,7 @@ typedef NS_ENUM(NSInteger, STPCardTextFieldState) {
if (hPadding >= STPPaymentCardTextFieldMinimumPadding) {
// Can just render everything at full size
// Do Nothing
}
else {
} else {
// Need to do selective view compression/hiding
if (self.focusedTextFieldForLayout == nil) {
@ -967,19 +944,16 @@ typedef NS_ENUM(NSInteger, STPCardTextFieldState) {
// Try hiding things in this order
if (panVisibility == STPCardTextFieldStateVisible) {
panVisibility = STPCardTextFieldStateCompressed;
}
else if (postalVisibility == STPCardTextFieldStateVisible) {
} else if (postalVisibility == STPCardTextFieldStateVisible) {
postalVisibility = STPCardTextFieldStateCompressed;
}
else {
} else {
// Can't hide anything else, set to minimum and stop
hPadding = STPPaymentCardTextFieldMinimumPadding;
break;
}
hPadding = calculateMinimumPaddingWithLocalVars();
}
}
else {
} else {
switch ((STPCardFieldType)self.focusedTextFieldForLayout.integerValue) {
case STPCardFieldTypeNumber: {
/*
@ -991,17 +965,13 @@ typedef NS_ENUM(NSInteger, STPCardTextFieldState) {
while (hPadding < STPPaymentCardTextFieldMinimumPadding) {
if (postalVisibility == STPCardTextFieldStateVisible) {
postalVisibility = STPCardTextFieldStateCompressed;
}
else if (postalVisibility == STPCardTextFieldStateCompressed) {
} else if (postalVisibility == STPCardTextFieldStateCompressed) {
postalVisibility = STPCardTextFieldStateHidden;
}
else if (cvcVisibility == STPCardTextFieldStateVisible) {
} else if (cvcVisibility == STPCardTextFieldStateVisible) {
cvcVisibility = STPCardTextFieldStateHidden;
}
else if (expiryVisibility == STPCardTextFieldStateVisible) {
} else if (expiryVisibility == STPCardTextFieldStateVisible) {
expiryVisibility = STPCardTextFieldStateHidden;
}
else {
} else {
hPadding = STPPaymentCardTextFieldMinimumPadding;
break;
}
@ -1019,14 +989,11 @@ typedef NS_ENUM(NSInteger, STPCardTextFieldState) {
while (hPadding < STPPaymentCardTextFieldMinimumPadding) {
if (panVisibility == STPCardTextFieldStateVisible) {
panVisibility = STPCardTextFieldStateCompressed;
}
else if (postalVisibility == STPCardTextFieldStateVisible) {
} else if (postalVisibility == STPCardTextFieldStateVisible) {
postalVisibility = STPCardTextFieldStateCompressed;
}
else if (postalVisibility == STPCardTextFieldStateCompressed) {
} else if (postalVisibility == STPCardTextFieldStateCompressed) {
postalVisibility = STPCardTextFieldStateHidden;
}
else {
} else {
hPadding = STPPaymentCardTextFieldMinimumPadding;
break;
}
@ -1046,14 +1013,11 @@ typedef NS_ENUM(NSInteger, STPCardTextFieldState) {
while (hPadding < STPPaymentCardTextFieldMinimumPadding) {
if (panVisibility == STPCardTextFieldStateVisible) {
panVisibility = STPCardTextFieldStateCompressed;
}
else if (postalVisibility == STPCardTextFieldStateVisible) {
} else if (postalVisibility == STPCardTextFieldStateVisible) {
postalVisibility = STPCardTextFieldStateCompressed;
}
else if (panVisibility == STPCardTextFieldStateCompressed) {
} else if (panVisibility == STPCardTextFieldStateCompressed) {
panVisibility = STPCardTextFieldStateHidden;
}
else {
} else {
hPadding = STPPaymentCardTextFieldMinimumPadding;
break;
}
@ -1071,14 +1035,11 @@ typedef NS_ENUM(NSInteger, STPCardTextFieldState) {
while (hPadding < STPPaymentCardTextFieldMinimumPadding) {
if (panVisibility == STPCardTextFieldStateVisible) {
panVisibility = STPCardTextFieldStateCompressed;
}
else if (panVisibility == STPCardTextFieldStateCompressed) {
} else if (panVisibility == STPCardTextFieldStateCompressed) {
panVisibility = STPCardTextFieldStateHidden;
}
else if (expiryVisibility == STPCardTextFieldStateVisible) {
} else if (expiryVisibility == STPCardTextFieldStateVisible) {
expiryVisibility = STPCardTextFieldStateHidden;
}
else {
} else {
hPadding = STPPaymentCardTextFieldMinimumPadding;
break;
}
@ -1131,8 +1092,7 @@ typedef NS_ENUM(NSInteger, STPCardTextFieldState) {
self.numberField.maskView = nil;
}];
}
}
else {
} else {
width = [self numberFieldFullWidth];
[UIView performWithoutAnimation:^{
self.numberField.maskView = nil;
@ -1235,8 +1195,7 @@ typedef void (^STPLayoutAnimationCompletionBlock)(BOOL completed);
options:0
animations:animations
completion:completion];
}
else {
} else {
animations();
}
}
@ -1586,8 +1545,7 @@ typedef NS_ENUM(NSInteger, STPFieldEditingTransitionCallSite) {
// CVC is on the back
return (UIViewAnimationOptionCurveEaseInOut | UIViewAnimationOptionTransitionFlipFromRight);
}
}
else if (newType != STPCardFieldTypeCVC
} else if (newType != STPCardFieldTypeCVC
&& oldType == STPCardFieldTypeCVC) {
// Transitioning to stop showing CVC

View File

@ -75,11 +75,9 @@
if (self.additionalPaymentOptions == STPPaymentOptionTypeAll) {
additionalPaymentOptionsDescription = @"STPPaymentOptionTypeAll";
}
else if (self.additionalPaymentOptions == STPPaymentOptionTypeNone) {
} else if (self.additionalPaymentOptions == STPPaymentOptionTypeNone) {
additionalPaymentOptionsDescription = @"STPPaymentOptionTypeNone";
}
else {
} else {
NSMutableArray *paymentOptions = [[NSMutableArray alloc] init];
if (self.additionalPaymentOptions & STPPaymentOptionTypeApplePay) {

View File

@ -19,7 +19,6 @@
#import "STPPaymentOptionTuple.h"
#import "STPPromise.h"
#import "STPShippingMethodsViewController.h"
#import "STPWeakStrongMacros.h"
#import "UINavigationController+Stripe_Completion.h"
#import "UIViewController+Stripe_ParentViewController.h"
#import "UIViewController+Stripe_Promises.h"
@ -39,33 +38,33 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
@interface STPPaymentContext() <STPPaymentOptionsViewControllerDelegate, STPShippingAddressViewControllerDelegate>
@property (nonatomic) STPPaymentConfiguration *configuration;
@property (nonatomic) STPTheme *theme;
@property (nonatomic) id<STPBackendAPIAdapter> apiAdapter;
@property (nonatomic) STPAPIClient *apiClient;
@property (nonatomic) STPPromise<STPPaymentOptionTuple *> *loadingPromise;
@property (nonatomic) STPPaymentConfiguration *configuration;
@property (nonatomic) STPTheme *theme;
@property (nonatomic) id<STPBackendAPIAdapter> apiAdapter;
@property (nonatomic) STPAPIClient *apiClient;
@property (nonatomic) STPPromise<STPPaymentOptionTuple *> *loadingPromise;
// these wrap hostViewController's promises because the hostVC is nil at init-time
@property (nonatomic) STPVoidPromise *willAppearPromise;
@property (nonatomic) STPVoidPromise *didAppearPromise;
// these wrap hostViewController's promises because the hostVC is nil at init-time
@property (nonatomic) STPVoidPromise *willAppearPromise;
@property (nonatomic) STPVoidPromise *didAppearPromise;
@property (nonatomic, weak) STPPaymentOptionsViewController *paymentOptionsViewController;
@property (nonatomic) id<STPPaymentOption> selectedPaymentOption;
@property (nonatomic) NSArray<id<STPPaymentOption>> *paymentOptions;
@property (nonatomic) STPAddress *shippingAddress;
@property (nonatomic) PKShippingMethod *selectedShippingMethod;
@property (nonatomic) NSArray<PKShippingMethod *> *shippingMethods;
@property (nonatomic, weak) STPPaymentOptionsViewController *paymentOptionsViewController;
@property (nonatomic) id<STPPaymentOption> selectedPaymentOption;
@property (nonatomic) NSArray<id<STPPaymentOption>> *paymentOptions;
@property (nonatomic) STPAddress *shippingAddress;
@property (nonatomic) PKShippingMethod *selectedShippingMethod;
@property (nonatomic) NSArray<PKShippingMethod *> *shippingMethods;
@property (nonatomic, assign) STPPaymentContextState state;
@property (nonatomic, assign) STPPaymentContextState state;
@property (nonatomic) STPPaymentContextAmountModel *paymentAmountModel;
@property (nonatomic) BOOL shippingAddressNeedsVerification;
@property (nonatomic) STPPaymentContextAmountModel *paymentAmountModel;
@property (nonatomic) BOOL shippingAddressNeedsVerification;
// If hostViewController was set to a nav controller, the original VC on top of the stack
@property (nonatomic, weak) UIViewController *originalTopViewController;
@property (nonatomic, nullable) PKPaymentAuthorizationViewController *applePayVC;
// If hostViewController was set to a nav controller, the original VC on top of the stack
@property (nonatomic, weak) UIViewController *originalTopViewController;
@property (nonatomic, nullable) PKPaymentAuthorizationViewController *applePayVC;
@end
@end
@implementation STPPaymentContext
@ -117,49 +116,49 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
STPCustomerContext *customerContext = (STPCustomerContext *)self.apiAdapter;
[customerContext clearCache];
}
WEAK(self);
__weak typeof(self) weakSelf = self;
self.loadingPromise = [[[STPPromise<STPPaymentOptionTuple *> new] onSuccess:^(STPPaymentOptionTuple *tuple) {
STRONG(self);
self.paymentOptions = tuple.paymentOptions;
self.selectedPaymentOption = tuple.selectedPaymentOption;
__strong typeof(self) strongSelf = weakSelf;
strongSelf.paymentOptions = tuple.paymentOptions;
strongSelf.selectedPaymentOption = tuple.selectedPaymentOption;
}] onFailure:^(NSError * _Nonnull error) {
STRONG(self);
if (self.hostViewController) {
[self.didAppearPromise onSuccess:^(__unused id value) {
if (self.paymentOptionsViewController) {
[self appropriatelyDismissPaymentOptionsViewController:self.paymentOptionsViewController completion:^{
[self.delegate paymentContext:self didFailToLoadWithError:error];
__strong typeof(self) strongSelf = weakSelf;
if (strongSelf.hostViewController) {
[strongSelf.didAppearPromise onSuccess:^(__unused id value) {
if (strongSelf.paymentOptionsViewController) {
[strongSelf appropriatelyDismissPaymentOptionsViewController:strongSelf.paymentOptionsViewController completion:^{
[strongSelf.delegate paymentContext:strongSelf didFailToLoadWithError:error];
}];
} else {
[self.delegate paymentContext:self didFailToLoadWithError:error];
[strongSelf.delegate paymentContext:strongSelf didFailToLoadWithError:error];
}
}];
}
}];
[self.apiAdapter retrieveCustomer:^(STPCustomer * _Nullable customer, NSError * _Nullable retrieveCustomerError) {
stpDispatchToMainThreadIfNecessary(^{
STRONG(self);
if (!self) {
__strong typeof(self) strongSelf = weakSelf;
if (!strongSelf) {
return;
}
if (retrieveCustomerError) {
[self.loadingPromise fail:retrieveCustomerError];
[strongSelf.loadingPromise fail:retrieveCustomerError];
return;
}
if (!self.shippingAddress && customer.shippingAddress) {
self.shippingAddress = customer.shippingAddress;
self.shippingAddressNeedsVerification = YES;
if (!strongSelf.shippingAddress && customer.shippingAddress) {
strongSelf.shippingAddress = customer.shippingAddress;
strongSelf.shippingAddressNeedsVerification = YES;
}
[self.apiAdapter listPaymentMethodsForCustomerWithCompletion:^(NSArray<STPPaymentMethod *> * _Nullable paymentMethods, NSError * _Nullable error) {
STRONG(self);
[strongSelf.apiAdapter listPaymentMethodsForCustomerWithCompletion:^(NSArray<STPPaymentMethod *> * _Nullable paymentMethods, NSError * _Nullable error) {
__strong typeof(self) strongSelf2 = weakSelf;
stpDispatchToMainThreadIfNecessary(^{
if (error) {
[self.loadingPromise fail:error];
[strongSelf2.loadingPromise fail:error];
return;
}
STPPaymentOptionTuple *paymentTuple = [STPPaymentOptionTuple tupleFilteredForUIWithPaymentMethods:paymentMethods selectedPaymentMethod:self.defaultPaymentMethod configuration:self.configuration];
[self.loadingPromise succeed:paymentTuple];
STPPaymentOptionTuple *paymentTuple = [STPPaymentOptionTuple tupleFilteredForUIWithPaymentMethods:paymentMethods selectedPaymentMethod:strongSelf2.defaultPaymentMethod configuration:strongSelf2.configuration];
[strongSelf2.loadingPromise succeed:paymentTuple];
});
}];
});
@ -170,7 +169,7 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
return !self.loadingPromise.completed;
}
// Disable transition animations in tests
// Disable transition animations in tests
- (BOOL)transitionAnimationsEnabled {
return NSClassFromString(@"XCTest") == nil;
}
@ -188,21 +187,21 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
- (void)setDelegate:(id<STPPaymentContextDelegate>)delegate {
_delegate = delegate;
WEAK(self);
__weak typeof(self) weakSelf = self;
[self.willAppearPromise voidOnSuccess:^{
STRONG(self);
if (self.delegate == delegate) {
[delegate paymentContextDidChange:self];
__strong typeof(self) strongSelf = weakSelf;
if (strongSelf.delegate == delegate) {
[delegate paymentContextDidChange:strongSelf];
}
}];
}
- (STPPromise<STPPaymentOptionTuple *> *)currentValuePromise {
WEAK(self);
__weak typeof(self) weakSelf = self;
return (STPPromise<STPPaymentOptionTuple *> *)[self.loadingPromise map:^id _Nonnull(__unused STPPaymentOptionTuple *value) {
STRONG(self);
return [STPPaymentOptionTuple tupleWithPaymentOptions:self.paymentOptions
selectedPaymentOption:self.selectedPaymentOption];
__strong typeof(self) strongSelf = weakSelf;
return [STPPaymentOptionTuple tupleWithPaymentOptions:strongSelf.paymentOptions
selectedPaymentOption:strongSelf.selectedPaymentOption];
}];
}
@ -269,8 +268,7 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
if (shippingMethods != nil && self.selectedShippingMethod != nil) {
if ([shippingMethods count] == 0) {
self.selectedShippingMethod = nil;
}
else if ([shippingMethods indexOfObject:self.selectedShippingMethod] == NSNotFound) {
} else if ([shippingMethods indexOfObject:self.selectedShippingMethod] == NSNotFound) {
self.selectedShippingMethod = [shippingMethods firstObject];
}
}
@ -296,30 +294,33 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
- (void)presentPaymentOptionsViewControllerWithNewState:(STPPaymentContextState)state {
NSCAssert(self.hostViewController != nil, @"hostViewController must not be nil on STPPaymentContext when calling pushPaymentOptionsViewController on it. Next time, set the hostViewController property first!");
WEAK(self);
__weak typeof(self) weakSelf = self;
[self.didAppearPromise voidOnSuccess:^{
STRONG(self);
if (self.state == STPPaymentContextStateNone) {
self.state = state;
STPPaymentOptionsViewController *paymentOptionsViewController = [[STPPaymentOptionsViewController alloc] initWithPaymentContext:self];
self.paymentOptionsViewController = paymentOptionsViewController;
paymentOptionsViewController.prefilledInformation = self.prefilledInformation;
paymentOptionsViewController.defaultPaymentMethod = self.defaultPaymentMethod;
paymentOptionsViewController.paymentOptionsViewControllerFooterView = self.paymentOptionsViewControllerFooterView;
paymentOptionsViewController.addCardViewControllerFooterView = self.addCardViewControllerFooterView;
__strong typeof(self) strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
if (strongSelf.state == STPPaymentContextStateNone) {
strongSelf.state = state;
STPPaymentOptionsViewController *paymentOptionsViewController = [[STPPaymentOptionsViewController alloc] initWithPaymentContext:strongSelf];
strongSelf.paymentOptionsViewController = paymentOptionsViewController;
paymentOptionsViewController.prefilledInformation = strongSelf.prefilledInformation;
paymentOptionsViewController.defaultPaymentMethod = strongSelf.defaultPaymentMethod;
paymentOptionsViewController.paymentOptionsViewControllerFooterView = strongSelf.paymentOptionsViewControllerFooterView;
paymentOptionsViewController.addCardViewControllerFooterView = strongSelf.addCardViewControllerFooterView;
if (@available(iOS 11, *)) {
paymentOptionsViewController.navigationItem.largeTitleDisplayMode = self.largeTitleDisplayMode;
paymentOptionsViewController.navigationItem.largeTitleDisplayMode = strongSelf.largeTitleDisplayMode;
}
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:paymentOptionsViewController];
navigationController.navigationBar.stp_theme = self.theme;
navigationController.navigationBar.stp_theme = strongSelf.theme;
if (@available(iOS 11, *)) {
navigationController.navigationBar.prefersLargeTitles = YES;
}
navigationController.modalPresentationStyle = self.modalPresentationStyle;
[self.hostViewController presentViewController:navigationController
animated:[self transitionAnimationsEnabled]
completion:nil];
navigationController.modalPresentationStyle = strongSelf.modalPresentationStyle;
[strongSelf.hostViewController presentViewController:navigationController
animated:[strongSelf transitionAnimationsEnabled]
completion:nil];
}
}];
}
@ -333,24 +334,24 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
navigationController = self.hostViewController.navigationController;
}
NSCAssert(self.hostViewController != nil, @"The payment context's hostViewController is not a navigation controller, or is not contained in one. Either make sure it is inside a navigation controller before calling pushPaymentOptionsViewController, or call presentPaymentOptionsViewController instead.");
WEAK(self);
__weak typeof(self) weakSelf = self;
[self.didAppearPromise voidOnSuccess:^{
STRONG(self);
if (self.state == STPPaymentContextStateNone) {
self.state = STPPaymentContextStateShowingRequestedViewController;
__strong typeof(self) strongSelf = weakSelf;
if (strongSelf.state == STPPaymentContextStateNone) {
strongSelf.state = STPPaymentContextStateShowingRequestedViewController;
STPPaymentOptionsViewController *paymentOptionsViewController = [[STPPaymentOptionsViewController alloc] initWithPaymentContext:self];
self.paymentOptionsViewController = paymentOptionsViewController;
paymentOptionsViewController.prefilledInformation = self.prefilledInformation;
paymentOptionsViewController.defaultPaymentMethod = self.defaultPaymentMethod;
paymentOptionsViewController.paymentOptionsViewControllerFooterView = self.paymentOptionsViewControllerFooterView;
paymentOptionsViewController.addCardViewControllerFooterView = self.addCardViewControllerFooterView;
STPPaymentOptionsViewController *paymentOptionsViewController = [[STPPaymentOptionsViewController alloc] initWithPaymentContext:strongSelf];
strongSelf.paymentOptionsViewController = paymentOptionsViewController;
paymentOptionsViewController.prefilledInformation = strongSelf.prefilledInformation;
paymentOptionsViewController.defaultPaymentMethod = strongSelf.defaultPaymentMethod;
paymentOptionsViewController.paymentOptionsViewControllerFooterView = strongSelf.paymentOptionsViewControllerFooterView;
paymentOptionsViewController.addCardViewControllerFooterView = strongSelf.addCardViewControllerFooterView;
if (@available(iOS 11, *)) {
paymentOptionsViewController.navigationItem.largeTitleDisplayMode = self.largeTitleDisplayMode;
paymentOptionsViewController.navigationItem.largeTitleDisplayMode = strongSelf.largeTitleDisplayMode;
}
[navigationController pushViewController:paymentOptionsViewController
animated:[self transitionAnimationsEnabled]];
animated:[strongSelf transitionAnimationsEnabled]];
}
}];
}
@ -365,8 +366,7 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
if (self.state == STPPaymentContextStateRequestingPayment) {
self.state = STPPaymentContextStateNone;
[self requestPayment];
}
else {
} else {
self.state = STPPaymentContextStateNone;
}
}];
@ -377,8 +377,7 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
if (self.state == STPPaymentContextStateRequestingPayment) {
[self didFinishWithStatus:STPPaymentStatusUserCancellation
error:nil];
}
else {
} else {
self.state = STPPaymentContextStateNone;
}
}];
@ -395,11 +394,11 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
// if we're the root of the navigation controller, we've been presented modally.
[viewController.presentingViewController dismissViewControllerAnimated:[self transitionAnimationsEnabled]
completion:^{
self.paymentOptionsViewController = nil;
if (completion) {
completion();
}
}];
self.paymentOptionsViewController = nil;
if (completion) {
completion();
}
}];
} else {
// otherwise, we've been pushed onto the stack.
UIViewController *destinationViewController = self.hostViewController;
@ -410,11 +409,11 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
[viewController.navigationController stp_popToViewController:destinationViewController
animated:[self transitionAnimationsEnabled]
completion:^{
self.paymentOptionsViewController = nil;
if (completion) {
completion();
}
}];
self.paymentOptionsViewController = nil;
if (completion) {
completion();
}
}];
}
}
@ -426,25 +425,25 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
- (void)presentShippingViewControllerWithNewState:(STPPaymentContextState)state {
NSCAssert(self.hostViewController != nil, @"hostViewController must not be nil on STPPaymentContext when calling presentShippingViewController on it. Next time, set the hostViewController property first!");
WEAK(self);
__weak typeof(self) weakSelf = self;
[self.didAppearPromise voidOnSuccess:^{
STRONG(self);
if (self.state == STPPaymentContextStateNone) {
self.state = state;
__strong typeof(self) strongSelf = weakSelf;
if (strongSelf.state == STPPaymentContextStateNone) {
strongSelf.state = state;
STPShippingAddressViewController *addressViewController = [[STPShippingAddressViewController alloc] initWithPaymentContext:self];
STPShippingAddressViewController *addressViewController = [[STPShippingAddressViewController alloc] initWithPaymentContext:strongSelf];
if (@available(iOS 11, *)) {
addressViewController.navigationItem.largeTitleDisplayMode = self.largeTitleDisplayMode;
addressViewController.navigationItem.largeTitleDisplayMode = strongSelf.largeTitleDisplayMode;
}
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:addressViewController];
navigationController.navigationBar.stp_theme = self.theme;
navigationController.navigationBar.stp_theme = strongSelf.theme;
if (@available(iOS 11, *)) {
navigationController.navigationBar.prefersLargeTitles = YES;
}
navigationController.modalPresentationStyle = self.modalPresentationStyle;
[self.hostViewController presentViewController:navigationController
animated:[self transitionAnimationsEnabled]
completion:nil];
navigationController.modalPresentationStyle = strongSelf.modalPresentationStyle;
[strongSelf.hostViewController presentViewController:navigationController
animated:[strongSelf transitionAnimationsEnabled]
completion:nil];
}
}];
}
@ -458,18 +457,18 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
navigationController = self.hostViewController.navigationController;
}
NSCAssert(self.hostViewController != nil, @"The payment context's hostViewController is not a navigation controller, or is not contained in one. Either make sure it is inside a navigation controller before calling pushShippingInfoViewController, or call presentShippingInfoViewController instead.");
WEAK(self);
__weak typeof(self) weakSelf = self;
[self.didAppearPromise voidOnSuccess:^{
STRONG(self);
if (self.state == STPPaymentContextStateNone) {
self.state = STPPaymentContextStateShowingRequestedViewController;
__strong typeof(self) strongSelf = weakSelf;
if (strongSelf.state == STPPaymentContextStateNone) {
strongSelf.state = STPPaymentContextStateShowingRequestedViewController;
STPShippingAddressViewController *addressViewController = [[STPShippingAddressViewController alloc] initWithPaymentContext:self];
STPShippingAddressViewController *addressViewController = [[STPShippingAddressViewController alloc] initWithPaymentContext:strongSelf];
if (@available(iOS 11, *)) {
addressViewController.navigationItem.largeTitleDisplayMode = self.largeTitleDisplayMode;
addressViewController.navigationItem.largeTitleDisplayMode = strongSelf.largeTitleDisplayMode;
}
[navigationController pushViewController:addressViewController
animated:[self transitionAnimationsEnabled]];
animated:[strongSelf transitionAnimationsEnabled]];
}
}];
}
@ -479,8 +478,7 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
if (self.state == STPPaymentContextStateRequestingPayment) {
[self didFinishWithStatus:STPPaymentStatusUserCancellation
error:nil];
}
else {
} else {
self.state = STPPaymentContextStateNone;
}
}];
@ -496,8 +494,7 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
completion(status, shippingValidationError, shippingMethods, selectedMethod);
}
}];
}
else {
} else {
if (completion) {
completion(STPShippingStatusValid, nil, nil, nil);
}
@ -530,10 +527,10 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
// if we're the root of the navigation controller, we've been presented modally.
[viewController.presentingViewController dismissViewControllerAnimated:[self transitionAnimationsEnabled]
completion:^{
if (completion) {
completion();
}
}];
if (completion) {
completion();
}
}];
} else {
// otherwise, we've been pushed onto the stack.
UIViewController *destinationViewController = self.hostViewController;
@ -544,10 +541,10 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
[viewController.navigationController stp_popToViewController:destinationViewController
animated:[self transitionAnimationsEnabled]
completion:^{
if (completion) {
completion();
}
}];
if (completion) {
completion();
}
}];
}
}
@ -573,74 +570,70 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
}
- (void)requestPayment {
WEAK(self);
__weak typeof(self) weakSelf = self;
[[[self.didAppearPromise voidFlatMap:^STPPromise * _Nonnull{
STRONG(self);
return self.loadingPromise;
__strong typeof(self) strongSelf = weakSelf;
return strongSelf.loadingPromise;
}] onSuccess:^(__unused STPPaymentOptionTuple *tuple) {
STRONG(self);
if (!self) {
__strong typeof(self) strongSelf = weakSelf;
if (!strongSelf) {
return;
}
if (self.state != STPPaymentContextStateNone) {
if (strongSelf.state != STPPaymentContextStateNone) {
return;
}
if (!self.selectedPaymentOption) {
[self presentPaymentOptionsViewControllerWithNewState:STPPaymentContextStateRequestingPayment];
}
else if ([self requestPaymentShouldPresentShippingViewController]) {
[self presentShippingViewControllerWithNewState:STPPaymentContextStateRequestingPayment];
}
else if ([self.selectedPaymentOption isKindOfClass:[STPPaymentMethod class]]) {
self.state = STPPaymentContextStateRequestingPayment;
STPPaymentResult *result = [[STPPaymentResult alloc] initWithPaymentMethod:(STPPaymentMethod *)self.selectedPaymentOption];
[self.delegate paymentContext:self didCreatePaymentResult:result completion:^(STPPaymentStatus status, NSError * _Nullable error) {
if (!strongSelf.selectedPaymentOption) {
[strongSelf presentPaymentOptionsViewControllerWithNewState:STPPaymentContextStateRequestingPayment];
} else if ([strongSelf requestPaymentShouldPresentShippingViewController]) {
[strongSelf presentShippingViewControllerWithNewState:STPPaymentContextStateRequestingPayment];
} else if ([strongSelf.selectedPaymentOption isKindOfClass:[STPPaymentMethod class]]) {
strongSelf.state = STPPaymentContextStateRequestingPayment;
STPPaymentResult *result = [[STPPaymentResult alloc] initWithPaymentMethod:(STPPaymentMethod *)strongSelf.selectedPaymentOption];
[strongSelf.delegate paymentContext:self didCreatePaymentResult:result completion:^(STPPaymentStatus status, NSError * _Nullable error) {
stpDispatchToMainThreadIfNecessary(^{
[self didFinishWithStatus:status error:error];
[strongSelf didFinishWithStatus:status error:error];
});
}];
}
else if ([self.selectedPaymentOption isKindOfClass:[STPApplePayPaymentOption class]]) {
NSCAssert(self.hostViewController != nil, @"hostViewController must not be nil on STPPaymentContext. Next time, set the hostViewController property first!");
self.state = STPPaymentContextStateRequestingPayment;
PKPaymentRequest *paymentRequest = [self buildPaymentRequest];
} else if ([strongSelf.selectedPaymentOption isKindOfClass:[STPApplePayPaymentOption class]]) {
NSCAssert(strongSelf.hostViewController != nil, @"hostViewController must not be nil on STPPaymentContext. Next time, set the hostViewController property first!");
strongSelf.state = STPPaymentContextStateRequestingPayment;
PKPaymentRequest *paymentRequest = [strongSelf buildPaymentRequest];
STPShippingAddressSelectionBlock shippingAddressHandler = ^(STPAddress *shippingAddress, STPShippingAddressValidationBlock completion) {
// Apple Pay always returns a partial address here, so we won't
// update self.shippingAddress or self.shippingMethods
if ([self.delegate respondsToSelector:@selector(paymentContext:didUpdateShippingAddress:completion:)]) {
[self.delegate paymentContext:self didUpdateShippingAddress:shippingAddress completion:^(STPShippingStatus status, __unused NSError *shippingValidationError, NSArray<PKShippingMethod *> *shippingMethods, __unused PKShippingMethod *selectedMethod) {
completion(status, shippingMethods, self.paymentSummaryItems);
if ([strongSelf.delegate respondsToSelector:@selector(paymentContext:didUpdateShippingAddress:completion:)]) {
[strongSelf.delegate paymentContext:strongSelf didUpdateShippingAddress:shippingAddress completion:^(STPShippingStatus status, __unused NSError *shippingValidationError, NSArray<PKShippingMethod *> *shippingMethods, __unused PKShippingMethod *selectedMethod) {
completion(status, shippingMethods, strongSelf.paymentSummaryItems);
}];
}
else {
completion(STPShippingStatusValid, self.shippingMethods, self.paymentSummaryItems);
} else {
completion(STPShippingStatusValid, strongSelf.shippingMethods, strongSelf.paymentSummaryItems);
}
};
STPShippingMethodSelectionBlock shippingMethodHandler = ^(PKShippingMethod *shippingMethod, STPPaymentSummaryItemCompletionBlock completion) {
self.selectedShippingMethod = shippingMethod;
[self.delegate paymentContextDidChange:self];
strongSelf.selectedShippingMethod = shippingMethod;
[strongSelf.delegate paymentContextDidChange:strongSelf];
completion(self.paymentSummaryItems);
};
STPPaymentAuthorizationBlock paymentHandler = ^(PKPayment *payment) {
self.selectedShippingMethod = payment.shippingMethod;
self.shippingAddress = [[STPAddress alloc] initWithPKContact:payment.shippingContact];
self.shippingAddressNeedsVerification = NO;
[self.delegate paymentContextDidChange:self];
if ([self.apiAdapter isKindOfClass:[STPCustomerContext class]]) {
STPCustomerContext *customerContext = (STPCustomerContext *)self.apiAdapter;
[customerContext updateCustomerWithShippingAddress:self.shippingAddress completion:nil];
strongSelf.selectedShippingMethod = payment.shippingMethod;
strongSelf.shippingAddress = [[STPAddress alloc] initWithPKContact:payment.shippingContact];
strongSelf.shippingAddressNeedsVerification = NO;
[strongSelf.delegate paymentContextDidChange:strongSelf];
if ([strongSelf.apiAdapter isKindOfClass:[STPCustomerContext class]]) {
STPCustomerContext *customerContext = (STPCustomerContext *)strongSelf.apiAdapter;
[customerContext updateCustomerWithShippingAddress:strongSelf.shippingAddress completion:nil];
}
};
STPApplePayPaymentMethodHandlerBlock applePayPaymentMethodHandler = ^(STPPaymentMethod *paymentMethod, STPPaymentStatusBlock completion) {
[self.apiAdapter attachPaymentMethodToCustomer:paymentMethod completion:^(NSError *attachPaymentMethodError) {
[strongSelf.apiAdapter attachPaymentMethodToCustomer:paymentMethod completion:^(NSError *attachPaymentMethodError) {
stpDispatchToMainThreadIfNecessary(^{
if (attachPaymentMethodError) {
completion(STPPaymentStatusError, attachPaymentMethodError);
} else {
STPPaymentResult *result = [[STPPaymentResult alloc] initWithPaymentMethod:paymentMethod];
[self.delegate paymentContext:self didCreatePaymentResult:result completion:^(STPPaymentStatus status, NSError * error) {
[strongSelf.delegate paymentContext:self didCreatePaymentResult:result completion:^(STPPaymentStatus status, NSError * error) {
// for Apple Pay, the didFinishWithStatus callback is fired later when Apple Pay VC finishes
completion(status, error);
}];
@ -648,31 +641,31 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
});
}];
};
self.applePayVC = [PKPaymentAuthorizationViewController
stp_controllerWithPaymentRequest:paymentRequest
apiClient:self.apiClient
onShippingAddressSelection:shippingAddressHandler
onShippingMethodSelection:shippingMethodHandler
onPaymentAuthorization:paymentHandler
onPaymentMethodCreation:applePayPaymentMethodHandler
onFinish:^(STPPaymentStatus status, NSError * _Nullable error) {
if (self.applePayVC.presentingViewController != nil) {
[self.hostViewController dismissViewControllerAnimated:[self transitionAnimationsEnabled]
completion:^{
[self didFinishWithStatus:status error:error];
}];
} else {
[self didFinishWithStatus:status error:error];
}
self.applePayVC = nil;
}];
[self.hostViewController presentViewController:self.applePayVC
animated:[self transitionAnimationsEnabled]
completion:nil];
strongSelf.applePayVC = [PKPaymentAuthorizationViewController
stp_controllerWithPaymentRequest:paymentRequest
apiClient:self.apiClient
onShippingAddressSelection:shippingAddressHandler
onShippingMethodSelection:shippingMethodHandler
onPaymentAuthorization:paymentHandler
onPaymentMethodCreation:applePayPaymentMethodHandler
onFinish:^(STPPaymentStatus status, NSError * _Nullable error) {
if (strongSelf.applePayVC.presentingViewController != nil) {
[strongSelf.hostViewController dismissViewControllerAnimated:[strongSelf transitionAnimationsEnabled]
completion:^{
[strongSelf didFinishWithStatus:status error:error];
}];
} else {
[strongSelf didFinishWithStatus:status error:error];
}
strongSelf.applePayVC = nil;
}];
[strongSelf.hostViewController presentViewController:strongSelf.applePayVC
animated:[strongSelf transitionAnimationsEnabled]
completion:nil];
}
}] onFailure:^(NSError *error) {
STRONG(self);
[self didFinishWithStatus:STPPaymentStatusError error:error];
__strong typeof(self) strongSelf = weakSelf;
[strongSelf didFinishWithStatus:STPPaymentStatusError error:error];
}];
}
@ -699,8 +692,7 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
if (requiredFields) {
paymentRequest.requiredShippingContactFields = requiredFields;
}
}
else {
} else {
paymentRequest.requiredShippingAddressFields = [STPAddress pkAddressFieldsFromStripeContactFields:self.configuration.requiredShippingAddressFields];
}
@ -710,8 +702,7 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
[orderedShippingMethods removeObject:self.selectedShippingMethod];
[orderedShippingMethods insertObject:self.selectedShippingMethod atIndex:0];
paymentRequest.shippingMethods = orderedShippingMethods;
}
else {
} else {
paymentRequest.shippingMethods = self.shippingMethods;
}
@ -726,20 +717,20 @@ typedef NS_ENUM(NSUInteger, STPPaymentContextState) {
+ (PKShippingType)pkShippingType:(STPShippingType)shippingType {
switch (shippingType) {
case STPShippingTypeShipping:
return PKShippingTypeShipping;
return PKShippingTypeShipping;
case STPShippingTypeDelivery:
return PKShippingTypeDelivery;
return PKShippingTypeDelivery;
}
}
static char kSTPPaymentCoordinatorAssociatedObjectKey;
static char kSTPPaymentCoordinatorAssociatedObjectKey;
- (void)artificiallyRetain:(NSObject *)host {
objc_setAssociatedObject(host, &kSTPPaymentCoordinatorAssociatedObjectKey, self, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark - STPAuthenticationContext
- (UIViewController *)authenticationPresentingViewController {
return self.hostViewController;
}
@ -755,6 +746,6 @@ static char kSTPPaymentCoordinatorAssociatedObjectKey;
}
}
@end
@end

View File

@ -37,8 +37,7 @@
NSInteger shippingAmount = (shippingMethod != nil) ? [shippingMethod.amount stp_amountWithCurrency:currency] : 0;
if (_paymentSummaryItems == nil) {
return _paymentAmount + shippingAmount;
}
else {
} else {
PKPaymentSummaryItem *lastItem = _paymentSummaryItems.lastObject;
return [lastItem.amount stp_amountWithCurrency:currency] + shippingAmount;
}
@ -63,8 +62,7 @@
[items insertObject:shippingItem atIndex:0];
}
return [items copy];
}
else {
} else {
if ([_paymentSummaryItems count] > 0 && shippingItem != nil) {
NSMutableArray *items = [_paymentSummaryItems mutableCopy];
PKPaymentSummaryItem *origTotalItem = [items lastObject];
@ -72,8 +70,7 @@
PKPaymentSummaryItem *totalItem = [PKPaymentSummaryItem summaryItemWithLabel:origTotalItem.label amount:newTotal];
[items removeLastObject];
return [[items arrayByAddingObjectsFromArray:@[shippingItem, totalItem]] copy];
}
else {
} else {
return _paymentSummaryItems;
}
}

View File

@ -80,8 +80,7 @@
NSArray *components = [clientSecret componentsSeparatedByString:@"_secret_"];
if (components.count >= 2 && [components[0] hasPrefix:@"pi_"]) {
return components[0];
}
else {
} else {
return nil;
}
}

View File

@ -137,22 +137,19 @@
- (NSAttributedString *)buildAttributedStringWithPaymentOption:(id<STPPaymentOption>)paymentOption selected:(BOOL)selected {
if ([paymentOption isKindOfClass:[STPCard class]]) {
return [self buildAttributedStringWithCard:(STPCard *)paymentOption selected:selected];
}
else if ([paymentOption isKindOfClass:[STPSource class]]) {
} else if ([paymentOption isKindOfClass:[STPSource class]]) {
STPSource *source = (STPSource *)paymentOption;
if (source.type == STPSourceTypeCard
&& source.cardDetails != nil) {
return [self buildAttributedStringWithCardSource:source selected:selected];
}
}
else if ([paymentOption isKindOfClass:[STPPaymentMethod class]]) {
} else if ([paymentOption isKindOfClass:[STPPaymentMethod class]]) {
STPPaymentMethod *paymentMethod = (STPPaymentMethod *)paymentOption;
if (paymentMethod.type == STPPaymentMethodTypeCard
&& paymentMethod.card != nil) {
return [self buildAttributedStringWithCardPaymentMethod:paymentMethod selected:selected];
}
}
else if ([paymentOption isKindOfClass:[STPApplePayPaymentOption class]]) {
} else if ([paymentOption isKindOfClass:[STPApplePayPaymentOption class]]) {
NSString *label = STPLocalizedString(@"Apple Pay", @"Text for Apple Pay payment method");
UIColor *primaryColor = [self primaryColorForPaymentOptionWithSelected:selected];
return [[NSAttributedString alloc] initWithString:label attributes:@{NSForegroundColorAttributeName: primaryColor}];

View File

@ -113,13 +113,11 @@ static NSInteger const PaymentOptionSectionAddCard = 1;
if ([self isAnyPaymentOptionDetachable]) {
// Show edit button
barButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(handleEditButtonTapped:)];
}
else {
} else {
// Show no button
barButtonItem = nil;
}
}
else {
} else {
// Show done button
barButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(handleDoneButtonTapped:)];
}
@ -238,8 +236,7 @@ static NSInteger const PaymentOptionSectionAddCard = 1;
BOOL selected = [paymentOption isEqual:self.selectedPaymentOption];
[cell configureWithPaymentOption:paymentOption theme:self.theme selected:selected];
}
else {
} else {
[cell configureForNewCardRowWithTheme:self.theme];
cell.accessibilityIdentifier = @"PaymentOptionsTableViewAddNewCardButtonIdentifier";
}
@ -328,8 +325,7 @@ static NSInteger const PaymentOptionSectionAddCard = 1;
// Notify delegate
[self.delegate internalViewControllerDidSelectPaymentOption:paymentOption];
}
else if (indexPath.section == PaymentOptionSectionAddCard) {
} else if (indexPath.section == PaymentOptionSectionAddCard) {
STPAddCardViewController *paymentCardViewController = [[STPAddCardViewController alloc] initWithConfiguration:self.configuration theme:self.theme];
paymentCardViewController.delegate = self;
paymentCardViewController.prefilledInformation = self.prefilledInformation;

View File

@ -23,7 +23,6 @@
#import "STPPaymentOptionsInternalViewController.h"
#import "STPPaymentOptionsViewController+Private.h"
#import "STPTheme.h"
#import "STPWeakStrongMacros.h"
#import "UIBarButtonItem+Stripe.h"
#import "UINavigationController+Stripe_Completion.h"
#import "UIViewController+Stripe_NavigationItemProxy.h"
@ -31,19 +30,19 @@
#import "UIViewController+Stripe_Promises.h"
@interface STPPaymentOptionsViewController()<STPPaymentOptionsInternalViewControllerDelegate, STPAddCardViewControllerDelegate>
@property (nonatomic) STPPaymentConfiguration *configuration;
@property (nonatomic) STPAddress *shippingAddress;
@property (nonatomic) id<STPBackendAPIAdapter> apiAdapter;
@property (nonatomic) STPAPIClient *apiClient;
@property (nonatomic) STPPromise<STPPaymentOptionTuple *> *loadingPromise;
@property (nonatomic, weak) STPPaymentActivityIndicatorView *activityIndicator;
@property (nonatomic, weak) UIViewController *internalViewController;
@end
@property (nonatomic) STPPaymentConfiguration *configuration;
@property (nonatomic) STPAddress *shippingAddress;
@property (nonatomic) id<STPBackendAPIAdapter> apiAdapter;
@property (nonatomic) STPAPIClient *apiClient;
@property (nonatomic) STPPromise<STPPaymentOptionTuple *> *loadingPromise;
@property (nonatomic, weak) STPPaymentActivityIndicatorView *activityIndicator;
@property (nonatomic, weak) UIViewController *internalViewController;
@end
@implementation STPPaymentOptionsViewController
- (instancetype)initWithPaymentContext:(STPPaymentContext *)paymentContext {
return [self initWithConfiguration:paymentContext.configuration
apiAdapter:paymentContext.apiAdapter
@ -52,14 +51,14 @@
shippingAddress:paymentContext.shippingAddress
delegate:paymentContext];
}
- (instancetype)initWithConfiguration:(STPPaymentConfiguration *)configuration
theme:(STPTheme *)theme
customerContext:(STPCustomerContext *)customerContext
delegate:(id<STPPaymentOptionsViewControllerDelegate>)delegate {
return [self initWithConfiguration:configuration theme:theme apiAdapter:customerContext delegate:delegate];
}
- (instancetype)initWithConfiguration:(STPPaymentConfiguration *)configuration
theme:(STPTheme *)theme
apiAdapter:(id<STPBackendAPIAdapter>)apiAdapter
@ -72,7 +71,7 @@
shippingAddress:nil
delegate:delegate];
}
- (STPPromise<STPPaymentOptionTuple *>*)retrievePaymentMethodsWithConfiguration:(STPPaymentConfiguration *)configuration
apiAdapter:(id<STPBackendAPIAdapter>)apiAdapter {
STPPromise<STPPaymentOptionTuple *> *promise = [STPPromise new];
@ -88,71 +87,70 @@
}];
return promise;
}
- (void)createAndSetupViews {
[super createAndSetupViews];
STPPaymentActivityIndicatorView *activityIndicator = [STPPaymentActivityIndicatorView new];
activityIndicator.animating = YES;
[self.view addSubview:activityIndicator];
self.activityIndicator = activityIndicator;
WEAK(self);
__weak typeof(self) weakSelf = self;
[self.loadingPromise onSuccess:^(STPPaymentOptionTuple *tuple) {
STRONG(self);
if (!self) {
__strong typeof(self) strongSelf = weakSelf;
if (!strongSelf) {
return;
}
UIViewController *internal;
if (tuple.paymentOptions.count > 0) {
STPCustomerContext *customerContext = ([self.apiAdapter isKindOfClass:[STPCustomerContext class]]) ? (STPCustomerContext *)self.apiAdapter : nil;
STPPaymentOptionsInternalViewController *payMethodsInternal = [[STPPaymentOptionsInternalViewController alloc] initWithConfiguration:self.configuration
STPCustomerContext *customerContext = ([strongSelf.apiAdapter isKindOfClass:[STPCustomerContext class]]) ? (STPCustomerContext *)strongSelf.apiAdapter : nil;
STPPaymentOptionsInternalViewController *payMethodsInternal = [[STPPaymentOptionsInternalViewController alloc] initWithConfiguration:strongSelf.configuration
customerContext:customerContext
theme:self.theme
prefilledInformation:self.prefilledInformation
shippingAddress:self.shippingAddress
theme:strongSelf.theme
prefilledInformation:strongSelf.prefilledInformation
shippingAddress:strongSelf.shippingAddress
paymentOptionTuple:tuple
delegate:self];
if (self.paymentOptionsViewControllerFooterView) {
payMethodsInternal.customFooterView = self.paymentOptionsViewControllerFooterView;
delegate:strongSelf];
if (strongSelf.paymentOptionsViewControllerFooterView) {
payMethodsInternal.customFooterView = strongSelf.paymentOptionsViewControllerFooterView;
}
if (self.addCardViewControllerFooterView) {
payMethodsInternal.addCardViewControllerCustomFooterView = self.addCardViewControllerFooterView;
if (strongSelf.addCardViewControllerFooterView) {
payMethodsInternal.addCardViewControllerCustomFooterView = strongSelf.addCardViewControllerFooterView;
}
internal = payMethodsInternal;
}
else {
STPAddCardViewController *addCardViewController = [[STPAddCardViewController alloc] initWithConfiguration:self.configuration theme:self.theme];
addCardViewController.delegate = self;
addCardViewController.prefilledInformation = self.prefilledInformation;
addCardViewController.shippingAddress = self.shippingAddress;
} else {
STPAddCardViewController *addCardViewController = [[STPAddCardViewController alloc] initWithConfiguration:strongSelf.configuration theme:self.theme];
addCardViewController.delegate = strongSelf;
addCardViewController.prefilledInformation = strongSelf.prefilledInformation;
addCardViewController.shippingAddress = strongSelf.shippingAddress;
internal = addCardViewController;
if (self.addCardViewControllerFooterView) {
addCardViewController.customFooterView = self.addCardViewControllerFooterView;
if (strongSelf.addCardViewControllerFooterView) {
addCardViewController.customFooterView = strongSelf.addCardViewControllerFooterView;
}
}
internal.stp_navigationItemProxy = self.navigationItem;
[self addChildViewController:internal];
internal.stp_navigationItemProxy = strongSelf.navigationItem;
[strongSelf addChildViewController:internal];
internal.view.alpha = 0;
[self.view insertSubview:internal.view belowSubview:self.activityIndicator];
[self.view addSubview:internal.view];
internal.view.frame = self.view.bounds;
[internal didMoveToParentViewController:self];
[strongSelf.view insertSubview:internal.view belowSubview:strongSelf.activityIndicator];
[strongSelf.view addSubview:internal.view];
internal.view.frame = strongSelf.view.bounds;
[internal didMoveToParentViewController:strongSelf];
[UIView animateWithDuration:0.2 animations:^{
self.activityIndicator.alpha = 0;
strongSelf.activityIndicator.alpha = 0;
internal.view.alpha = 1;
} completion:^(__unused BOOL finished) {
self.activityIndicator.animating = NO;
strongSelf.activityIndicator.animating = NO;
}];
[self.navigationItem setRightBarButtonItem:internal.stp_navigationItemProxy.rightBarButtonItem animated:YES];
self.internalViewController = internal;
[strongSelf.navigationItem setRightBarButtonItem:internal.stp_navigationItemProxy.rightBarButtonItem animated:YES];
strongSelf.internalViewController = internal;
}];
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
CGFloat centerX = (self.view.frame.size.width - self.activityIndicator.frame.size.width) / 2;
@ -160,24 +158,24 @@
self.activityIndicator.frame = CGRectMake(centerX, centerY, self.activityIndicator.frame.size.width, self.activityIndicator.frame.size.height);
self.internalViewController.view.frame = self.view.bounds;
}
- (void)updateAppearance {
[super updateAppearance];
self.activityIndicator.tintColor = self.theme.accentColor;
}
- (void)finishWithPaymentOption:(id<STPPaymentOption>)paymentOption {
if ([self.delegate respondsToSelector:@selector(paymentOptionsViewController:didSelectPaymentOption:)]) {
[self.delegate paymentOptionsViewController:self didSelectPaymentOption:paymentOption];
}
[self.delegate paymentOptionsViewControllerDidFinish:self];
}
- (void)internalViewControllerDidSelectPaymentOption:(id<STPPaymentOption>)paymentOption {
[self finishWithPaymentOption:paymentOption];
}
- (void)internalViewControllerDidDeletePaymentOption:(id<STPPaymentOption>)paymentOption {
if ([self.delegate isKindOfClass:[STPPaymentContext class]]) {
// Notify payment context to update its copy of payment methods
@ -185,22 +183,22 @@
[paymentContext removePaymentOption:paymentOption];
}
}
- (void)internalViewControllerDidCreatePaymentMethod:(STPPaymentMethod *)paymentMethod completion:(STPErrorBlock)completion {
[self.apiAdapter attachPaymentMethodToCustomer:paymentMethod completion:^(NSError *error) {
stpDispatchToMainThreadIfNecessary(^{
completion(error);
if (!error) {
STPPromise<STPPaymentOptionTuple *> *promise = [self retrievePaymentMethodsWithConfiguration:self.configuration apiAdapter:self.apiAdapter];
WEAK(self);
__weak typeof(self) weakSelf = self;
[promise onSuccess:^(STPPaymentOptionTuple *tuple) {
STRONG(self);
if (!self) {
__strong typeof(self) strongSelf = weakSelf;
if (!strongSelf) {
return;
}
STPPaymentOptionTuple *paymentTuple = [STPPaymentOptionTuple tupleWithPaymentOptions:tuple.paymentOptions selectedPaymentOption:paymentMethod];
if ([self.internalViewController isKindOfClass:[STPPaymentOptionsInternalViewController class]]) {
STPPaymentOptionsInternalViewController *paymentOptionsVC = (STPPaymentOptionsInternalViewController *)self.internalViewController;
if ([strongSelf.internalViewController isKindOfClass:[STPPaymentOptionsInternalViewController class]]) {
STPPaymentOptionsInternalViewController *paymentOptionsVC = (STPPaymentOptionsInternalViewController *)strongSelf.internalViewController;
[paymentOptionsVC updateWithPaymentOptionTuple:paymentTuple];
}
}];
@ -209,32 +207,31 @@
});
}];
}
- (void)internalViewControllerDidCancel {
[self.delegate paymentOptionsViewControllerDidCancel:self];
}
- (void)handleCancelTapped:(__unused id)sender {
[self.delegate paymentOptionsViewControllerDidCancel:self];
}
- (void)addCardViewControllerDidCancel:(__unused STPAddCardViewController *)addCardViewController {
// Add card is only our direct delegate if there are no other payment methods possible
// and we skipped directly to this screen. In this case, a cancel from it is the same as a cancel to us.
[self.delegate paymentOptionsViewControllerDidCancel:self];
}
- (void)addCardViewController:(__unused STPAddCardViewController *)addCardViewController
didCreatePaymentMethod:(STPPaymentMethod *)paymentMethod
completion:(STPErrorBlock)completion {
[self internalViewControllerDidCreatePaymentMethod:paymentMethod completion:completion];
}
- (void)dismissWithCompletion:(STPVoidBlock)completion {
if ([self stp_isAtRootOfNavigationController]) {
[self.presentingViewController dismissViewControllerAnimated:YES completion:completion];
}
else {
} else {
UIViewController *previous = self.navigationController.viewControllers.firstObject;
for (UIViewController *viewController in self.navigationController.viewControllers) {
if (viewController == self) {
@ -245,11 +242,11 @@
[self.navigationController stp_popToViewController:previous animated:YES completion:completion];
}
}
@end
@end
@implementation STPPaymentOptionsViewController (Private)
- (instancetype)initWithConfiguration:(STPPaymentConfiguration *)configuration
apiAdapter:(id<STPBackendAPIAdapter>)apiAdapter
loadingPromise:(STPPromise<STPPaymentOptionTuple *> *)loadingPromise
@ -264,34 +261,34 @@
_apiAdapter = apiAdapter;
_loadingPromise = loadingPromise;
_delegate = delegate;
self.navigationItem.title = STPLocalizedString(@"Loading…", @"Title for screen when data is still loading from the network.");
WEAK(self);
__weak typeof(self) weakSelf = self;
[[[self.stp_didAppearPromise voidFlatMap:^STPPromise * _Nonnull{
return loadingPromise;
}] onSuccess:^(STPPaymentOptionTuple *tuple) {
STRONG(self);
if (!self) {
__strong typeof(self) strongSelf = weakSelf;
if (!strongSelf) {
return;
}
if (tuple.selectedPaymentOption) {
if ([self.delegate respondsToSelector:@selector(paymentOptionsViewController:didSelectPaymentOption:)]) {
[self.delegate paymentOptionsViewController:self
didSelectPaymentOption:tuple.selectedPaymentOption];
if ([strongSelf.delegate respondsToSelector:@selector(paymentOptionsViewController:didSelectPaymentOption:)]) {
[strongSelf.delegate paymentOptionsViewController:strongSelf
didSelectPaymentOption:tuple.selectedPaymentOption];
}
}
}] onFailure:^(NSError *error) {
STRONG(self);
if (!self) {
__strong typeof(self) strongSelf = weakSelf;
if (!strongSelf) {
return;
}
[self.delegate paymentOptionsViewController:self didFailToLoadWithError:error];
[strongSelf.delegate paymentOptionsViewController:strongSelf didFailToLoadWithError:error];
}];
}
return self;
}
@end
@end

View File

@ -38,8 +38,7 @@
if ([countryCode isEqualToString:@"US"]) {
return [STPCardValidator sanitizedNumericStringForString:string].length <= 10;
}
else {
} else {
return YES;
}
}
@ -50,8 +49,7 @@
if ([countryCode isEqualToString:@"US"]) {
return [STPCardValidator sanitizedNumericStringForString:string].length == 10;
}
else {
} else {
return YES;
}
}

View File

@ -23,17 +23,14 @@ static NSString *const STPCountryCodeUnitedStates = @"US";
if ([self postalCodeIsRequiredForCountryCode:countryCode]) {
if ([sanitizedCountryCode isEqualToString:STPCountryCodeUnitedStates]) {
return [self validationStateForUSPostalCode:postalCode];
}
else {
} else {
if (postalCode.length > 0) {
return STPCardValidationStateValid;
}
else {
} else {
return STPCardValidationStateIncomplete;
}
}
}
else {
} else {
return STPCardValidationStateValid;
}
}
@ -48,8 +45,7 @@ static NSUInteger countOfCharactersFromSetInString(NSString * _Nonnull string, N
range = [string rangeOfCharacterFromSet:cs options:(NSStringCompareOptions)kNilOptions range:NSMakeRange(lastPosition, string.length - lastPosition)];
if (range.location == NSNotFound) {
break;
}
else {
} else {
count += range.length;
lastPosition = NSMaxRange(range);
}
@ -69,34 +65,28 @@ static NSUInteger countOfCharactersFromSetInString(NSString * _Nonnull string, N
if (!firstFiveIsNumeric) {
// Non-numbers included in first five characters
return STPCardValidationStateInvalid;
}
else if (firstFiveLength < 5) {
} else if (firstFiveLength < 5) {
// Incomplete ZIP with only numbers
return STPCardValidationStateIncomplete;
}
else if (totalLength == 5) {
} else if (totalLength == 5) {
// Valid 5 digit zip
return STPCardValidationStateValid;
}
else {
} else {
// ZIP+4 territory
NSUInteger numberOfDigits = countOfCharactersFromSetInString(postalCode, [NSCharacterSet stp_asciiDigitCharacterSet]);
if (numberOfDigits > 9) {
// Too many digits
return STPCardValidationStateInvalid;
}
else if (numberOfDigits == totalLength) {
} else if (numberOfDigits == totalLength) {
// All numeric postal code entered
if (numberOfDigits == 9) {
return STPCardValidationStateValid;
}
else {
} else {
return STPCardValidationStateIncomplete;
}
}
else if ((numberOfDigits + 1) == totalLength) {
} else if ((numberOfDigits + 1) == totalLength) {
// Possibly has a separator character for ZIP+4, check to see if
// its in the right place
@ -105,17 +95,14 @@ static NSUInteger countOfCharactersFromSetInString(NSString * _Nonnull string, N
// Non-digit is in right position to be separator
if (numberOfDigits == 9) {
return STPCardValidationStateValid;
}
else {
} else {
return STPCardValidationStateIncomplete;
}
}
else {
} else {
// Non-digit is in wrong position to be separator
return STPCardValidationStateInvalid;
}
}
else {
} else {
// Not a valid zip code (too many non-numeric characters)
return STPCardValidationStateInvalid;
}
@ -132,8 +119,7 @@ static NSUInteger countOfCharactersFromSetInString(NSString * _Nonnull string, N
if ([sanitizedCountryCode isEqualToString:STPCountryCodeUnitedStates]) {
return [self formattedSanitizedUSZipCodeFromString:postalCode
usage:usage];
}
else {
} else {
return postalCode;
}
@ -172,8 +158,7 @@ static NSUInteger countOfCharactersFromSetInString(NSString * _Nonnull string, N
+ (BOOL)postalCodeIsRequiredForCountryCode:(NSString *)countryCode {
if (countryCode == nil) {
return YES;
}
else {
} else {
return (![[self countriesWithNoPostalCodes] containsObject:countryCode.uppercaseString]);
}
}

View File

@ -9,7 +9,6 @@
#import "STPPromise.h"
#import "STPDispatchFunctions.h"
#import "STPWeakStrongMacros.h"
@interface STPPromise<T>()
@ -76,13 +75,13 @@
}
- (void)completeWith:(STPPromise *)promise {
WEAK(self);
__weak typeof(self) weakSelf = self;
[[promise onSuccess:^(id value) {
STRONG(self);
[self succeed:value];
__strong typeof(self) strongSelf = weakSelf;
[strongSelf succeed:value];
}] onFailure:^(NSError * _Nonnull error) {
STRONG(self);
[self fail:error];
__strong typeof(self) strongSelf = weakSelf;
[strongSelf fail:error];
}];
}
@ -161,12 +160,9 @@
}
- (void)voidCompleteWith:(STPVoidPromise *)promise {
WEAK(self);
[[promise voidOnSuccess:^{
STRONG(self);
[self succeed];
}] onFailure:^(NSError *error) {
STRONG(self);
[self fail:error];
}];
}

View File

@ -17,7 +17,6 @@
#import "STPSource.h"
#import "STPSourceWeChatPayDetails.h"
#import "STPURLCallbackHandler.h"
#import "STPWeakStrongMacros.h"
#import "NSError+Stripe.h"
NSString *const STPRedirectContextErrorDomain = @"STPRedirectContextErrorDomain";
@ -145,15 +144,18 @@ typedef void (^STPBoolCompletionBlock)(BOOL success);
self.state = STPRedirectContextStateInProgress;
[self subscribeToURLAndForegroundNotifications];
WEAK(self)
__weak typeof(self) weakSelf = self;
[self performAppRedirectIfPossibleWithCompletion:^(BOOL success) {
if (success) {
return;
}
STRONG(self)
__strong typeof(self) strongSelf = weakSelf;
if (strongSelf == nil) {
return;
}
// Redirect failed...
if (self.source.type == STPSourceTypeWeChatPay) {
if (strongSelf.source.type == STPSourceTypeWeChatPay) {
// ...and this Source doesn't support web-based redirect finish with an error.
NSError *error = [[NSError alloc] initWithDomain:STPRedirectContextErrorDomain
code:STPRedirectContextAppRedirectError
@ -162,17 +164,16 @@ typedef void (^STPBoolCompletionBlock)(BOOL success);
STPErrorMessageKey: @"Redirecting to WeChat failed. Only offer WeChat Pay if the WeChat app is installed.",
}];
stpDispatchToMainThreadIfNecessary(^{
[self handleRedirectCompletionWithError:error shouldDismissViewController:NO];
[strongSelf handleRedirectCompletionWithError:error shouldDismissViewController:NO];
});
} else {
// ...reset our state and try a web redirect
self.state = STPRedirectContextStateNotStarted;
[self unsubscribeFromNotifications];
strongSelf.state = STPRedirectContextStateNotStarted;
[strongSelf unsubscribeFromNotifications];
if ([SFSafariViewController class] != nil) {
[self startSafariViewControllerRedirectFlowFromViewController:presentingViewController];
}
else {
[self startSafariAppRedirectFlow];
[strongSelf startSafariViewControllerRedirectFlowFromViewController:presentingViewController];
} else {
[strongSelf startSafariAppRedirectFlow];
}
}
}];
@ -286,8 +287,7 @@ typedef void (^STPBoolCompletionBlock)(BOOL success);
[application openURL:nativeURL options:@{} completionHandler:^(BOOL success) {
onCompletion(success);
}];
}
else {
} else {
BOOL opened = [application openURL:nativeURL];
onCompletion(opened);
}

View File

@ -92,8 +92,7 @@
_addressViewModel.delegate = self;
if (shippingAddress != nil) {
_addressViewModel.address = shippingAddress;
}
else if (prefilledInformation.shippingAddress != nil) {
} else if (prefilledInformation.shippingAddress != nil) {
_addressViewModel.address = prefilledInformation.shippingAddress;
}
self.title = [self titleForShippingType:self.configuration.shippingType];
@ -232,14 +231,12 @@
theme:self.theme];
nextViewController.delegate = self;
[self.navigationController pushViewController:nextViewController animated:YES];
}
else {
} else {
[self.delegate shippingAddressViewController:self
didFinishWithAddress:address
shippingMethod:nil];
}
}
else {
} else {
[self handleShippingValidationError:shippingValidationError];
}
}];
@ -277,8 +274,7 @@
- (void)dismissWithCompletion:(STPVoidBlock)completion {
if ([self stp_isAtRootOfNavigationController]) {
[self.presentingViewController dismissViewControllerAnimated:YES completion:completion];
}
else {
} else {
UIViewController *previous = self.navigationController.viewControllers.firstObject;
for (UIViewController *viewController in self.navigationController.viewControllers) {
if (viewController == self) {
@ -372,8 +368,7 @@
return STPLocalizedString(@"Delivery", @"Title for delivery info form");
break;
}
}
else {
} else {
return STPLocalizedString(@"Contact", @"Title for contact info form");
}
}
@ -388,8 +383,7 @@
return STPLocalizedString(@"Delivery Address", @"Title for delivery address entry section");
break;
}
}
else {
} else {
return STPLocalizedString(@"Contact", @"Title for contact info form");
}
}

View File

@ -65,8 +65,7 @@
NSInteger amount = [method.amount stp_amountWithCurrency:currency];
if (amount == 0) {
self.amountLabel.text = STPLocalizedString(@"Free", @"Label for free shipping method");
}
else {
} else {
NSDecimalNumber *number = [NSDecimalNumber stp_decimalNumberWithAmount:amount
currency:currency];
self.amountLabel.text = [self.numberFormatter stringFromNumber:number];

View File

@ -42,8 +42,7 @@ static NSString *const STPShippingMethodCellReuseIdentifier = @"STPShippingMetho
_shippingMethods = methods;
if (selectedMethod != nil && [methods indexOfObject:selectedMethod] != NSNotFound) {
_selectedShippingMethod = selectedMethod;
}
else {
} else {
_selectedShippingMethod = [methods stp_boundSafeObjectAtIndex:0];
}

View File

@ -261,11 +261,9 @@
if (source.type == STPSourceTypeCard) {
source.cardDetails = [STPSourceCardDetails decodedObjectFromAPIResponse:source.details];
}
else if (source.type == STPSourceTypeSEPADebit) {
} else if (source.type == STPSourceTypeSEPADebit) {
source.sepaDebitDetails = [STPSourceSEPADebitDetails decodedObjectFromAPIResponse:source.details];
}
else if (source.type == STPSourceTypeWeChatPay) {
} else if (source.type == STPSourceTypeWeChatPay) {
source.weChatPayDetails = [STPSourceWeChatPayDetails decodedObjectFromAPIResponse:source.details];
}
@ -277,8 +275,7 @@
- (UIImage *)image {
if (self.type == STPSourceTypeCard && self.cardDetails != nil) {
return [STPImageLibrary brandImageForCardBrand:self.cardDetails.brand];
}
else {
} else {
return [STPImageLibrary brandImageForCardBrand:STPCardBrandUnknown];
}
}
@ -286,8 +283,7 @@
- (UIImage *)templateImage {
if (self.type == STPSourceTypeCard && self.cardDetails != nil) {
return [STPImageLibrary templatedBrandImageForCardBrand:self.cardDetails.brand];
}
else {
} else {
return [STPImageLibrary templatedBrandImageForCardBrand:STPCardBrandUnknown];
}
}
@ -300,8 +296,7 @@
if (self.cardDetails != nil) {
NSString *brand = [STPCard stringFromBrand:self.cardDetails.brand];
return [NSString stringWithFormat:@"%@ %@", brand, self.cardDetails.last4];
}
else {
} else {
return [STPCard stringFromBrand:STPCardBrandUnknown];
}
case STPSourceTypeGiropay:

View File

@ -26,8 +26,7 @@
completion:^(NSString *__unused newString, NSRange tagRange) {
if (tagRange.location == NSNotFound) {
tagsToRange[tag] = [NSValue valueWithRange:tagRange];
}
else {
} else {
NSRange interiorRange = NSMakeRange(tagRange.location + tag.length + 2,
tagRange.length);
interiorRangesToTags[[NSValue valueWithRange:interiorRange]] = tag;
@ -42,11 +41,9 @@
if (range1.location < range2.location) {
return NSOrderedAscending;
}
else if (range1.location > range2.location) {
} else if (range1.location > range2.location) {
return NSOrderedDescending;
}
else {
} else {
return NSOrderedSame;
}
}];

View File

@ -177,8 +177,7 @@ static UIFont *STPThemeDefaultMediumFont;
- (UIBarStyle)barStyleForColor:(UIColor *)color {
if ([STPColorUtils colorIsBright:color]) {
return UIBarStyleDefault;
}
else {
} else {
return UIBarStyleBlack;
}
}

View File

@ -20,8 +20,7 @@ NS_ASSUME_NONNULL_BEGIN
+ (BOOL)handleStripeURLCallbackWithURL:(NSURL *)url FAUXPAS_IGNORED_ON_LINE(UnusedMethod) {
if (url) {
return [[STPURLCallbackHandler shared] handleURLCallback:url];
}
else {
} else {
return NO;
}
}

View File

@ -1,19 +0,0 @@
//
// STPWeakStrongMacros.h
// Stripe
//
// Created by Brian Dorfman on 7/28/16.
// Copyright © 2016 Stripe, Inc. All rights reserved.
//
/*
Based on @weakify() and @strongify() from
https://github.com/jspahrsummers/libextc
*/
#define WEAK(var) __weak typeof(var) weak_##var = var;
#define STRONG(var) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wshadow\"") \
__strong typeof(var) var = weak_##var; \
_Pragma("clang diagnostic pop") \

View File

@ -20,8 +20,7 @@ NS_ASSUME_NONNULL_BEGIN
self.bounds.size.width - (insets.left + insets.right),
self.bounds.size.height);
return safeBounds;
}
else {
} else {
return self.bounds;
}
}

View File

@ -513,8 +513,7 @@
XCTAssertNotEqualObjects([address valueForKey:property],
[copiedAddress valueForKey:property],
@"%@", property);
}
else {
} else {
XCTAssertEqualObjects([address valueForKey:property],
[copiedAddress valueForKey:property],
@"%@", property);

View File

@ -163,8 +163,7 @@
XCTAssertNotEqualObjects([cardParams valueForKey:property],
[copiedCardParams valueForKey:property],
@"%@", property);
}
else {
} else {
XCTAssertEqualObjects([cardParams valueForKey:property],
[copiedCardParams valueForKey:property],
@"%@", property);

View File

@ -74,8 +74,7 @@
XCTAssertNotNil(token);
XCTAssertNotNil(token.tokenId);
XCTAssertEqual(token.type, STPTokenTypeAccount);
}
else {
} else {
XCTAssertNil(token);
XCTAssertNotNil(error);
}

View File

@ -66,10 +66,10 @@
NSCAssert(success, @"Error recording requests: %@", recordingError);
// Make sure to fail, to remind ourselves to turn this off
__weak typeof(self) weakself = self;
__weak typeof(self) weakSelf = self;
[self addTeardownBlock:^{
// Like XCTFail, but avoiding a retain cycle
_XCTPrimitiveFail(weakself, @"Network traffic for %@ has been recorded - re-run with self.recordingMode = NO for this test to succeed", [weakself name]);
_XCTPrimitiveFail(weakSelf, @"Network traffic for %@ has been recorded - re-run with self.recordingMode = NO for this test to succeed", [weakSelf name]);
}];
} else {
// Stubs are evaluated in the reverse order that they are added, so if the network is hit and no other stub is matched, raise an exception

View File

@ -16,7 +16,6 @@
#import "STPRedirectContext+Private.h"
#import "STPTestUtils.h"
#import "STPURLCallbackHandler.h"
#import "STPWeakStrongMacros.h"
@interface STPRedirectContext (Testing)
- (void)unsubscribeFromNotifications;
@ -393,8 +392,8 @@
RedirectContext's completion block and dismiss method should be called.
*/
- (void)testSafariViewControllerRedirectFlow_failedInitialLoad_iOS11Plus API_AVAILABLE(ios(11)) {
if (@available(iOS 11, *)) {}
else {
if (@available(iOS 11, *)) {
} else {
// see testSafariViewControllerRedirectFlow_failedInitialLoad_preiOS11
return; // Skipping
}
@ -441,8 +440,8 @@
*/
- (void)testSafariViewControllerRedirectFlow_failedInitialLoadAfterRedirect_iOS11Plus API_AVAILABLE(ios(11)) {
if (@available(iOS 11, *)) {}
else {
if (@available(iOS 11, *)) {
} else {
// see testSafariViewControllerRedirectFlow_failedInitialLoad_preiOS11
return; // Skipping
}
@ -596,8 +595,7 @@
OCMStub([applicationMock openURL:[OCMArg any]
options:[OCMArg any]
completionHandler:([OCMArg invokeBlockWithArgs:@YES, nil])]);
}
else {
} else {
OCMStub([applicationMock openURL:[OCMArg any]]).andReturn(YES);
}
@ -611,8 +609,7 @@
OCMVerify([applicationMock openURL:[OCMArg isEqual:sourceURL]
options:[OCMArg isEqual:@{}]
completionHandler:[OCMArg isNotNil]]);
}
else {
} else {
OCMVerify([applicationMock openURL:[OCMArg isEqual:sourceURL]]);
}
@ -640,8 +637,7 @@
OCMReject([applicationMock openURL:[OCMArg any]
options:[OCMArg any]
completionHandler:[OCMArg any]]);
}
else {
} else {
OCMReject([applicationMock openURL:[OCMArg any]]);
}
@ -685,8 +681,7 @@
OCMStub([applicationMock openURL:[OCMArg any]
options:[OCMArg any]
completionHandler:([OCMArg invokeBlockWithArgs:@YES, nil])]);
}
else {
} else {
OCMStub([applicationMock openURL:[OCMArg any]]).andReturn(YES);
}
@ -700,8 +695,7 @@
OCMVerify([applicationMock openURL:[OCMArg isEqual:sourceURL]
options:[OCMArg isEqual:@{}]
completionHandler:[OCMArg isNotNil]]);
}
else {
} else {
OCMVerify([applicationMock openURL:[OCMArg isEqual:sourceURL]]);
}
@ -738,8 +732,7 @@
OCMStub([applicationMock openURL:[OCMArg any]
options:[OCMArg any]
completionHandler:([OCMArg invokeBlockWithArgs:@NO, nil])]);
}
else {
} else {
OCMStub([applicationMock openURL:[OCMArg any]]).andReturn(NO);
}
@ -753,8 +746,7 @@
OCMVerify([applicationMock openURL:[OCMArg isEqual:sourceURL]
options:[OCMArg isEqual:@{}]
completionHandler:[OCMArg isNotNil]]);
}
else {
} else {
OCMVerify([applicationMock openURL:[OCMArg isEqual:sourceURL]]);
}