Skip to content

Commit

Permalink
Lint Examples and stragglers (stripe#2220)
Browse files Browse the repository at this point in the history
* Lint StripePaymentsUI

* Lint Testers

* Lint Examples and stragglers
  • Loading branch information
eurias-stripe authored Jan 13, 2023
1 parent dc30bfd commit c8b7064
Show file tree
Hide file tree
Showing 102 changed files with 847 additions and 853 deletions.
8 changes: 7 additions & 1 deletion .swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ disabled_rules:
- reduce_boolean
- unused_setter_value
- notification_center_detachment
- private_outlet

opt_in_rules:
- colon
Expand All @@ -54,7 +55,6 @@ opt_in_rules:
- prohibited_super_call
- redundant_nil_coalescing
- return_arrow_whitespace
- single_test_class
- sorted_imports
- statement_position
- trailing_newline
Expand All @@ -65,11 +65,17 @@ opt_in_rules:
# - weak_delegate
# - discouraged_object_literal
# - unowned_variable_capture
# - indentation_width
# - single_test_class

excluded:
- Package.swift
- Pods
- Carthage
- Tests/installation_tests
- vendor
- build*
- .build

identifier_name:
allowed_symbols: _
Expand Down
3 changes: 1 addition & 2 deletions Example/AppClipExample/Project.swift
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,6 @@ let project = Project(
"AppClipExampleClipUITests",
]),
runAction: .runAction(executable: "AppClipExampleClip")
)
),
]
)

22 changes: 11 additions & 11 deletions Example/AppClipExample/Shared/ApplePayModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,56 +6,56 @@
//

import Foundation
import StripeApplePay
import PassKit
import StripeApplePay

class MyApplePayBackendModel : NSObject, ObservableObject, ApplePayContextDelegate {
class MyApplePayBackendModel: NSObject, ObservableObject, ApplePayContextDelegate {
@Published var paymentStatus: STPApplePayContext.PaymentStatus?
@Published var lastPaymentError: Error?

func pay() {
// Configure a payment request
let pr = StripeAPI.paymentRequest(withMerchantIdentifier: "merchant.com.stripetest.appclipexample", country: "US", currency: "USD")

// You'd generally want to configure at least `.postalAddress` here.
// We don't require anything here, as we don't want to enter an address
// in CI.
pr.requiredShippingContactFields = []
pr.requiredBillingContactFields = []

// Configure shipping methods
let firstClassShipping = PKShippingMethod(label: "First Class Mail", amount: NSDecimalNumber(string: "10.99"))
firstClassShipping.detail = "Arrives in 3-5 days"
firstClassShipping.identifier = "firstclass"
let rocketRidesShipping = PKShippingMethod(label: "Rocket Rides courier", amount: NSDecimalNumber(string: "10.99"))
rocketRidesShipping.detail = "Arrives in 1-2 hours"
rocketRidesShipping.identifier = "rocketrides"
pr.shippingMethods = [
pr.shippingMethods = [
firstClassShipping,
rocketRidesShipping
rocketRidesShipping,
]

// Build payment summary items
// (You'll generally want to configure these based on the selected address and shipping method.
pr.paymentSummaryItems = [
PKPaymentSummaryItem(label: "A very nice computer", amount: NSDecimalNumber(string: "19.99")),
PKPaymentSummaryItem(label: "Shipping", amount: NSDecimalNumber(string: "10.99")),
PKPaymentSummaryItem(label: "Stripe Computer Shop", amount: NSDecimalNumber(string: "29.99"))
PKPaymentSummaryItem(label: "Stripe Computer Shop", amount: NSDecimalNumber(string: "29.99")),
]

// Present the Apple Pay Context:
let applePayContext = STPApplePayContext(paymentRequest: pr, delegate: self)
applePayContext?.presentApplePay()
}

func applePayContext(_ context: STPApplePayContext, didCreatePaymentMethod paymentMethod: StripeAPI.PaymentMethod, paymentInformation: PKPayment, completion: @escaping STPIntentClientSecretCompletionBlock) {
// When the Apple Pay sheet is confirmed, create a PaymentIntent on your backend from the provided PKPayment information.
BackendModel.shared.fetchPaymentIntent() { secret in
BackendModel.shared.fetchPaymentIntent { secret in
if let clientSecret = secret {
// Call the completion block with the PaymentIntent's client secret.
completion(clientSecret, nil)
} else {
completion(nil, NSError())
completion(nil, NSError()) // swiftlint:disable:this discouraged_direct_init
}
}
}
Expand Down
22 changes: 11 additions & 11 deletions Example/AppClipExample/Shared/BackendModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ class BackendModel {
// You can replace this with your own backend URL.
// Visit https://glitch.com/edit/#!/stripe-integration-tester and click "remix".
static let backendAPIURL = URL(string: "https://stripe-integration-tester.glitch.me")!

static let returnURL = "stp-integration-tester://stripe-redirect"

public static let shared = BackendModel()

func fetchPaymentIntent(completion: @escaping (String?) -> Void) {
let params = ["integration_method": "Apple Pay"]
getAPI(method: "create_pi", params: params) { (json) in
Expand All @@ -27,7 +27,7 @@ class BackendModel {
completion(paymentIntentClientSecret)
}
}

func loadPublishableKey(completion: @escaping (String) -> Void) {
let params = ["integration_method": "Apple Pay"]
getAPI(method: "get_pub_key", params: params) { (json) in
Expand All @@ -38,22 +38,22 @@ class BackendModel {
}
}
}
private func getAPI(method: String, params: [String : Any] = [:], completion: @escaping ([String : Any]) -> Void) {

private func getAPI(method: String, params: [String: Any] = [:], completion: @escaping ([String: Any]) -> Void) {
var request = URLRequest(url: Self.backendAPIURL.appendingPathComponent(method))
request.httpMethod = "POST"

request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in

let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, _, error) in
guard let unwrappedData = data,
let json = try? JSONSerialization.jsonObject(with: unwrappedData, options: []) as? [String : Any] else {
let json = try? JSONSerialization.jsonObject(with: unwrappedData, options: []) as? [String: Any] else {
if let data = data {
print("\(String(decoding: data, as: UTF8.self))")
} else {
print("\(error ?? NSError())")
print("\(error ?? NSError())") // swiftlint:disable:this discouraged_direct_init
}
return
}
Expand Down
6 changes: 3 additions & 3 deletions Example/AppClipExample/Shared/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@
// Created by David Estes on 1/7/22.
//

import SwiftUI
import StripeApplePay
import SwiftUI

struct ContentView: View {
@StateObject var model = MyApplePayBackendModel()
@State var ready = false

var body: some View {
if ready {
VStack {
PaymentButton() {
PaymentButton {
model.pay()
}
.padding()
Expand Down
24 changes: 12 additions & 12 deletions Example/AppClipExample/Shared/PaymentButton.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,20 @@ Abstract:
A button that hosts PKPaymentButton from Apple's Fruta example app.
*/

import SwiftUI
import PassKit
import SwiftUI

struct PaymentButton: View {
var action: () -> Void

var height: CGFloat {
#if os(macOS)
return 30
#else
return 45
#endif
}

var body: some View {
Representable(action: action)
.frame(minWidth: 100, maxWidth: 400)
Expand All @@ -40,41 +40,41 @@ extension PaymentButton {
#else
typealias ViewRepresentable = NSViewRepresentable
#endif

struct Representable: ViewRepresentable {
var action: () -> Void

init(action: @escaping () -> Void) {
self.action = action
}

func makeCoordinator() -> Coordinator {
Coordinator(action: action)
}

#if os(iOS)
func makeUIView(context: Context) -> UIView {
context.coordinator.button
}

func updateUIView(_ rootView: UIView, context: Context) {
context.coordinator.action = action
}
#else
func makeNSView(context: Context) -> NSView {
context.coordinator.button
}

func updateNSView(_ rootView: NSView, context: Context) {
context.coordinator.action = action
}
#endif
}

class Coordinator: NSObject {
var action: () -> Void
var button = PKPaymentButton(paymentButtonType: .buy, paymentButtonStyle: .automatic)

init(action: @escaping () -> Void) {
self.action = action
super.init()
Expand All @@ -85,7 +85,7 @@ extension PaymentButton {
button.target = self
#endif
}

@objc
func callback(_ sender: Any) {
action()
Expand Down
7 changes: 4 additions & 3 deletions Example/Basic Integration/Basic Integration/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
) -> Bool {
// Disable hardware keyboards in CI:
#if targetEnvironment(simulator)
if (ProcessInfo.processInfo.environment["UITesting"] != nil) {
if ProcessInfo.processInfo.environment["UITesting"] != nil {
let setHardwareLayout = NSSelectorFromString("setHardwareLayout:")
UITextInputMode.activeInputModes
.filter({ $0.responds(to: setHardwareLayout) })
.forEach { $0.perform(setHardwareLayout, with: nil) }
}
#endif

let rootVC = BrowseProductsViewController()
let navigationController = UINavigationController(rootViewController: rootVC)
let window = UIWindow(frame: UIScreen.main.bounds)
Expand Down Expand Up @@ -54,7 +54,8 @@ class AppDelegate: UIResponder, UIApplicationDelegate {

// This method is where you handle URL opens if you are using univeral link URLs (eg "https://example.com/stripe_ios_callback")
func application(
_ application: UIApplication, continue userActivity: NSUserActivity,
_ application: UIApplication,
continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void
) -> Bool {
if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,8 @@ extension BrowseProductsViewController: UICollectionViewDelegateFlowLayout {
// MARK: - UICollectionViewDelegateFlowLayout

func collectionView(
_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
let width = view.frame.size.width * 0.45
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class CheckoutViewController: UIViewController {
// https://github.com/stripe/example-mobile-backend/tree/v18.1.0, click "Deploy to Heroku", and follow
// the instructions (don't worry, it's free). Replace nil on the line below with your
// Heroku URL (it looks like https://blazing-sunrise-1234.herokuapp.com ).
var backendBaseURL: String? = nil
var backendBaseURL: String?

// 3) Optionally, to enable Apple Pay, follow the instructions at https://stripe.com/docs/apple-pay
// to create an Apple Merchant ID. Replace nil on the line below with it (it looks like merchant.com.yourappname).
Expand Down Expand Up @@ -280,7 +280,8 @@ extension CheckoutViewController: STPPaymentContextDelegate {
}
}
func paymentContext(
_ paymentContext: STPPaymentContext, didCreatePaymentResult paymentResult: STPPaymentResult,
_ paymentContext: STPPaymentContext,
didCreatePaymentResult paymentResult: STPPaymentResult,
completion: @escaping STPPaymentStatusBlock
) {
// Create the PaymentIntent on the backend
Expand Down Expand Up @@ -314,7 +315,6 @@ extension CheckoutViewController: STPPaymentContextDelegate {
// A real app should retry this request if it was a network error.
print("Failed to create a Payment Intent: \(error)")
completion(.error, error)
break
}
}
}
Expand Down Expand Up @@ -393,7 +393,8 @@ extension CheckoutViewController: STPPaymentContextDelegate {
// Note: this delegate method is optional. If you do not need to collect a
// shipping method from your user, you should not implement this method.
func paymentContext(
_ paymentContext: STPPaymentContext, didUpdateShippingAddress address: STPAddress,
_ paymentContext: STPPaymentContext,
didUpdateShippingAddress address: STPAddress,
completion: @escaping STPShippingMethodsCompletionBlock
) {
let upsGround = PKShippingMethod()
Expand Down
6 changes: 4 additions & 2 deletions Example/Basic Integration/Basic Integration/MyAPIClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,17 @@ class MyAPIClient: NSObject, STPCustomerEphemeralKeyProvider {
}

func createPaymentIntent(
products: [Product], shippingMethod: PKShippingMethod?, country: String? = nil,
products: [Product],
shippingMethod: PKShippingMethod?,
country: String? = nil,
completion: @escaping ((Result<String, Error>) -> Void)
) {
let url = self.baseURL.appendingPathComponent("create_payment_intent")
var params: [String: Any] = [
"metadata": [
// example-mobile-backend allows passing metadata through to Stripe
"payment_request_id": "B3E611D1-5FA1-4410-9CEC-00958A5126CB"
]
],
]
params["products"] = products.map({ (p) -> String in
return p.emoji
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ extension XCUIElement {

class BasicIntegrationUITests: XCTestCase {
var app: XCUIApplication!

override func setUp() {
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
Expand Down Expand Up @@ -244,7 +244,7 @@ class BasicIntegrationUITests: XCTestCase {

class FrenchAndBelizeBasicIntegrationUITests: XCTestCase {
var app: XCUIApplication!

override func setUp() {
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
Expand Down
2 changes: 1 addition & 1 deletion Example/Basic Integration/Project.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,6 @@ let project = Project(
]),
testAction: .targets(["BasicIntegrationUITests"]),
runAction: .runAction(executable: "Basic Integration")
)
),
]
)
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ struct APIClient {
urlRequest.httpMethod = httpMethod
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-type")

URLSession.shared.dataTask(with: urlRequest) { data, response, error in
URLSession.shared.dataTask(with: urlRequest) { data, _, error in
DispatchQueue.main.async {
guard
error == nil,
Expand Down
Loading

0 comments on commit c8b7064

Please sign in to comment.