Skip to content

Commit

Permalink
address swiftlint warnings for BraintreeCore
Browse files Browse the repository at this point in the history
  • Loading branch information
jaxdesmarais committed Jul 12, 2024
1 parent a70aa0d commit 91c3227
Show file tree
Hide file tree
Showing 23 changed files with 158 additions and 86 deletions.
8 changes: 7 additions & 1 deletion Sources/BraintreeCore/Analytics/BTAnalyticsService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ class BTAnalyticsService: Equatable {

// MARK: - Internal Properties

// swiftlint:disable force_unwrapping
/// The FPTI URL to post all analytic events.
static let url = URL(string: "https://api.paypal.com")!
// swiftlint:enable force_unwrapping

/// The HTTP client for communication with the analytics service endpoint. Exposed for testing.
var http: BTHTTP?
Expand Down Expand Up @@ -131,7 +133,11 @@ class BTAnalyticsService: Equatable {
if await !BTAnalyticsService.events.isEmpty {
do {
let configuration = try await apiClient.fetchConfiguration()
let postParameters = await createAnalyticsEvent(config: configuration, sessionID: apiClient.metadata.sessionID, events: Self.events.allValues)
let postParameters = await createAnalyticsEvent(
config: configuration,
sessionID: apiClient.metadata.sessionID,
events: Self.events.allValues
)
http?.post("v1/tracking/batch/events", parameters: postParameters) { _, _, _ in }
await Self.events.removeAll()
} catch {
Expand Down
11 changes: 7 additions & 4 deletions Sources/BraintreeCore/Analytics/FPTIBatchData.swift
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import UIKit

// swiftlint:disable nesting
/// The POST body for a batch upload of FPTI events
struct FPTIBatchData: Codable {

let events: [EventsContainer] // Single-element "events" array required by FPTI formatting

init(metadata: Metadata, events fptiEvents: [Event]?) {
self.events = [EventsContainer(
metadata: metadata,
fptiEvents: fptiEvents ?? []
)]
self.events = [
EventsContainer(
metadata: metadata,
fptiEvents: fptiEvents ?? []
)
]
}

struct EventsContainer: Codable {
Expand Down
11 changes: 5 additions & 6 deletions Sources/BraintreeCore/Authorization/BTClientToken.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import Foundation

/// An authorization string used to initialize the Braintree SDK
@_documentation(visibility: private)
@objcMembers public class BTClientToken: NSObject, NSCoding, NSCopying, ClientAuthorization {

@objcMembers
public class BTClientToken: NSObject, NSCoding, NSCopying, ClientAuthorization {

// NEXT_MAJOR_VERSION (v7): properties exposed for Objective-C interoperability + Drop-in access.
// Once the entire SDK is in Swift, determine if we want public properties to be internal and
// what we can make internal without breaking the Drop-in.
Expand Down Expand Up @@ -38,8 +39,7 @@ import Foundation
// Client token must be decoded first because the other values are retrieved from it
self.json = try Self.decodeClientToken(clientToken)

guard let authorizationFingerprint = json["authorizationFingerprint"].asString(),
!authorizationFingerprint.isEmpty else {
guard let authorizationFingerprint = json["authorizationFingerprint"].asString(), !authorizationFingerprint.isEmpty else {
throw BTClientTokenError.invalidAuthorizationFingerprint
}

Expand Down Expand Up @@ -113,8 +113,7 @@ import Foundation
// MARK: - NSObject override

public override func isEqual(_ object: Any?) -> Bool {
guard object is BTClientToken,
let otherToken = object as? BTClientToken else {
guard object is BTClientToken, let otherToken = object as? BTClientToken else {
return false
}

Expand Down
2 changes: 2 additions & 0 deletions Sources/BraintreeCore/Authorization/BTClientTokenError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public enum BTClientTokenError: Error, CustomNSError, LocalizedError, Equatable
}
}

// swiftlint:disable line_length
public var errorDescription: String? {
switch self {
case .invalidAuthorizationFingerprint:
Expand All @@ -51,4 +52,5 @@ public enum BTClientTokenError: Error, CustomNSError, LocalizedError, Equatable
return "Failed to decode client token. \(description)"
}
}
// swiftlint:enable line_length
}
6 changes: 3 additions & 3 deletions Sources/BraintreeCore/Authorization/TokenizationKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ class TokenizationKey: ClientAuthorization {
guard tokenizationKey.range(of: pattern, options: .regularExpression) != nil else { return nil }

let tokenizationKeyParts = tokenizationKey.split(separator: "_", maxSplits: 3)
let environment: String = String(tokenizationKeyParts[0])
let merchantID: String = String(tokenizationKeyParts[2])
let environment = String(tokenizationKeyParts[0])
let merchantID = String(tokenizationKeyParts[2])

var components: URLComponents = URLComponents()
var components = URLComponents()
components.scheme = environment == "development" ? "http" : "https"

guard let host = host(for: environment) else { return nil }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,3 @@ public enum TokenizationKeyError: Int, Error, CustomNSError, LocalizedError, Equ
}
}
}

26 changes: 20 additions & 6 deletions Sources/BraintreeCore/BTAPIClient.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Foundation

// swiftlint:disable type_body_length file_length
/// This class acts as the entry point for accessing the Braintree APIs via common HTTP methods performed on API endpoints.
/// - Note: It also manages authentication via tokenization key and provides access to a merchant's gateway configuration.
@objcMembers public class BTAPIClient: NSObject, BTHTTPNetworkTiming {
Expand Down Expand Up @@ -46,7 +47,7 @@ import Foundation
switch authorizationType {
case .tokenizationKey:
do {
self.authorization = try TokenizationKey(authorization)
self.authorization = try TokenizationKey(authorization)
} catch {
return nil
}
Expand All @@ -68,7 +69,7 @@ import Foundation
http?.networkTimingDelegate = self

// Kickoff the background request to fetch the config
fetchOrReturnRemoteConfiguration { configuration, error in
fetchOrReturnRemoteConfiguration { _, _ in
// No-op
}
}
Expand Down Expand Up @@ -148,7 +149,7 @@ import Foundation
"session_id": metadata.sessionID
]

get("v1/payment_methods", parameters: parameters) { body, response, error in
get("v1/payment_methods", parameters: parameters) { body, _, error in
if let error {
completion(nil, error)
return
Expand All @@ -158,7 +159,10 @@ import Foundation

body?["paymentMethods"].asArray()?.forEach { paymentInfo in
let type: String? = paymentInfo["type"].asString()
let paymentMethodNonce: BTPaymentMethodNonce? = BTPaymentMethodNonceParser.shared.parseJSON(paymentInfo, withParsingBlockForType: type)
let paymentMethodNonce: BTPaymentMethodNonce? = BTPaymentMethodNonceParser.shared.parseJSON(
paymentInfo,
withParsingBlockForType: type
)

if let paymentMethodNonce {
paymentMethodNonces.append(paymentMethodNonce)
Expand Down Expand Up @@ -269,7 +273,13 @@ import Foundation
}

let postParameters = BTAPIRequest(requestBody: parameters, metadata: metadata, httpType: httpType)
http(for: httpType)?.post(path, configuration: configuration, parameters: postParameters, headers: headers, completion: completion)
http(for: httpType)?.post(
path,
configuration: configuration,
parameters: postParameters,
headers: headers,
completion: completion
)
}
}

Expand Down Expand Up @@ -339,7 +349,11 @@ import Foundation
let pattern: String = "([a-zA-Z0-9]+)_[a-zA-Z0-9]+_([a-zA-Z0-9_]+)"
guard let regularExpression = try? NSRegularExpression(pattern: pattern) else { return nil }

let tokenizationKeyMatch: NSTextCheckingResult? = regularExpression.firstMatch(in: authorization, options: [], range: NSRange(location: 0, length: authorization.count))
let tokenizationKeyMatch: NSTextCheckingResult? = regularExpression.firstMatch(
in: authorization,
options: [],
range: NSRange(location: 0, length: authorization.count)
)

return tokenizationKeyMatch != nil ? .tokenizationKey : .clientToken
}
Expand Down
12 changes: 5 additions & 7 deletions Sources/BraintreeCore/BTAppContextSwitcher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ import UIKit

// MARK: - Private Properties

private var appContextSwitchClients = [BTAppContextSwitchClient.Type]()
private var appContextSwitchClients: [BTAppContextSwitchClient.Type] = []

// MARK: - Public Methods

/// Determine whether the return URL can be handled.
Expand All @@ -35,11 +35,9 @@ import UIKit
/// - Returns: `true` when the SDK has handled the URL successfully
@objc(handleOpenURL:)
@discardableResult public func handleOpen(_ url: URL) -> Bool {
for appContextSwitchClient in appContextSwitchClients {
if appContextSwitchClient.canHandleReturnURL(url) {
appContextSwitchClient.handleReturnURL(url)
return true
}
for appContextSwitchClient in appContextSwitchClients where appContextSwitchClient.canHandleReturnURL(url) {
appContextSwitchClient.handleReturnURL(url)
return true
}
return false
}
Expand Down
2 changes: 2 additions & 0 deletions Sources/BraintreeCore/BTCoreConstants.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ import Foundation

static let graphQLVersion: String = "2018-03-06"

// swiftlint:disable force_unwrapping
static let payPalProductionURL = URL(string: "https://api.paypal.com")!

static let payPalSandboxURL = URL(string: "https://api.sandbox.paypal.com")!
// swiftlint:enable force_unwrapping

// MARK: - BTHTTPError Constants

Expand Down
2 changes: 1 addition & 1 deletion Sources/BraintreeCore/BTGraphQLErrorTree.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import Foundation
class BTGraphQLErrorTree {

let message: String
let rootNode: BTGraphQLMultiErrorNode = BTGraphQLMultiErrorNode()
let rootNode = BTGraphQLMultiErrorNode()

init(message: String) {
self.message = message
Expand Down
19 changes: 15 additions & 4 deletions Sources/BraintreeCore/BTGraphQLHTTP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,26 @@ class BTGraphQLHTTP: BTHTTP {

// MARK: - Properties

private let exceptionName: NSExceptionName = NSExceptionName("")
private let exceptionName = NSExceptionName("")

// MARK: - Overrides

override func get(_ path: String, configuration: BTConfiguration? = nil, parameters: Encodable? = nil, completion: @escaping RequestCompletion) {
override func get(
_ path: String,
configuration: BTConfiguration? = nil,
parameters: Encodable? = nil,
completion: @escaping RequestCompletion
) {
NSException(name: exceptionName, reason: "GET is unsupported").raise()
}

override func post(_ path: String, configuration: BTConfiguration? = nil, parameters: [String: Any]? = nil, headers: [String: String]? = nil, completion: @escaping RequestCompletion) {
override func post(
_ path: String,
configuration: BTConfiguration? = nil,
parameters: [String: Any]? = nil,
headers: [String: String]? = nil,
completion: @escaping RequestCompletion
) {
httpRequest(method: "POST", configuration: configuration, parameters: parameters, completion: completion)
}

Expand Down Expand Up @@ -103,7 +114,7 @@ class BTGraphQLHTTP: BTHTTP {
let body = BTJSON(value: json)

// Success case
if let _ = body.asDictionary(), body["errors"].asArray() == nil {
if body.asDictionary() != nil, body["errors"].asArray() == nil {
callCompletionAsync(with: completion, body: body, response: httpResponse, error: nil)
return
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/BraintreeCore/BTGraphQLMultiErrorNode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class BTGraphQLMultiErrorNode: BTGraphQLErrorNode {
return result
}

func toDictionary() -> [String : Any] {
func toDictionary() -> [String: Any] {
var result: [String: Any] = ["field": field]
result["fieldErrors"] = mapChildrenInOrder { $0.toDictionary() }
return result
Expand Down
2 changes: 1 addition & 1 deletion Sources/BraintreeCore/BTGraphQLSingleErrorNode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class BTGraphQLSingleErrorNode: BTGraphQLErrorNode {
self.code = code
}

func toDictionary() -> [String : Any] {
func toDictionary() -> [String: Any] {
var result = ["field": field, "message": message]
if let code = code {
result["code"] = code
Expand Down
Loading

0 comments on commit 91c3227

Please sign in to comment.