Skip to content

Commit b95bf4c

Browse files
authored
refact(OptimizelyJSON): Refactored to return decoded value. (#319)
1 parent f39784c commit b95bf4c

File tree

6 files changed

+133
-153
lines changed

6 files changed

+133
-153
lines changed

Sources/Optimizely/OptimizelyJSON+ObjC.swift

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,4 @@ extension OptimizelyJSON {
4343
public func objcToMap() -> [String: Any] {
4444
return self.toMap()
4545
}
46-
47-
@available(swift, obsoleted: 1.0)
48-
@objc(getValueWithJsonPath:schema:)
49-
/// Populates the schema passed by the user
50-
///
51-
/// - Parameters:
52-
/// - jsonPath: Key path for the value.
53-
/// - schema: Schema to populate.
54-
/// - Returns: true if value decoded successfully
55-
public func objcGetValue(jsonPath: String, schema: UnsafeMutablePointer<AnyObject>) -> Bool {
56-
return self.getValue(jsonPath: jsonPath, schema: &schema.pointee)
57-
}
5846
}

Sources/Optimizely/OptimizelyJSON.swift

Lines changed: 38 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import Foundation
1919
public class OptimizelyJSON: NSObject {
2020

2121
private lazy var logger = OPTLoggerFactory.getLogger()
22-
private typealias SchemaHandler = (Any) -> Bool
22+
private typealias ValueHandler<T> = (Any) -> T?
2323
var payload: String?
2424
var map = [String: Any]()
2525

@@ -67,58 +67,63 @@ public class OptimizelyJSON: NSObject {
6767
return map
6868
}
6969

70-
/// Populates the decodable schema passed by the user
70+
/// Returns decoded value for jsonPath
71+
///
72+
/// If JSON Data is {"k1":true, "k2":{"k3":"v3"}}
73+
///
74+
/// Set jsonPath to "k2" to access {"k3":"v3"} or set it to "k2.k3" to access "v3"
75+
/// Set it to nil or empty to access the entire JSON data.
7176
///
7277
/// - Parameters:
7378
/// - jsonPath: Key path for the value.
74-
/// - schema: Decodable schema to populate.
75-
/// - Returns: true if value decoded successfully
76-
public func getValue<T: Decodable>(jsonPath: String?, schema: inout T) -> Bool {
77-
func populateDecodableSchema(value: Any) -> Bool {
79+
/// - Returns: Value if decoded successfully
80+
public func getValue<T: Decodable>(jsonPath: String? = nil) -> T? {
81+
func handler(value: Any) -> T? {
7882
guard JSONSerialization.isValidJSONObject(value) else {
79-
// Try and assign value directly to schema
83+
// Try and typecast value to required return type
8084
if let v = value as? T {
81-
schema = v
82-
return true
85+
return v
8386
}
84-
logger.e(.failedToAssignValueToSchema)
85-
return false
87+
logger.e(.failedToAssignValue)
88+
return nil
8689
}
87-
// Try to decode value into schema
90+
// Try to decode value into return type
8891
guard let jsonData = try? JSONSerialization.data(withJSONObject: value, options: []),
8992
let decodedValue = try? JSONDecoder().decode(T.self, from: jsonData) else {
90-
logger.e(.failedToAssignValueToSchema)
91-
return false
93+
logger.e(.failedToAssignValue)
94+
return nil
9295
}
93-
schema = decodedValue
94-
return true
96+
return decodedValue
9597
}
96-
return getValue(jsonPath: jsonPath, schemaHandler: populateDecodableSchema(value:))
98+
return getValue(jsonPath: jsonPath, valueHandler: handler(value:))
9799
}
98100

99-
/// Populates the schema passed by the user
101+
/// Returns parsed value for jsonPath
102+
///
103+
/// If JSON Data is {"k1":true, "k2":{"k3":"v3"}}
104+
///
105+
/// Set jsonPath to "k2" to access {"k3":"v3"} or set it to "k2.k3" to access "v3"
106+
/// Set it to nil or empty to access the entire JSON data.
100107
///
101108
/// - Parameters:
102109
/// - jsonPath: Key path for the value.
103-
/// - schema: Schema to populate.
104-
/// - Returns: true if value decoded successfully
105-
public func getValue<T>(jsonPath: String?, schema: inout T) -> Bool {
106-
func populateSchema(value: Any) -> Bool {
110+
/// - Returns: Value if parsed successfully
111+
public func getValue<T>(jsonPath: String?) -> T? {
112+
func handler(value: Any) -> T? {
107113
guard let v = value as? T else {
108-
self.logger.e(.failedToAssignValueToSchema)
109-
return false
114+
self.logger.e(.failedToAssignValue)
115+
return nil
110116
}
111-
schema = v
112-
return true
117+
return v
113118
}
114-
return getValue(jsonPath: jsonPath, schemaHandler: populateSchema(value:))
119+
return getValue(jsonPath: jsonPath, valueHandler: handler(value:))
115120
}
116121

117-
private func getValue(jsonPath: String?, schemaHandler: SchemaHandler) -> Bool {
122+
private func getValue<T>(jsonPath: String?, valueHandler: ValueHandler<T>) -> T? {
118123

119124
guard let path = jsonPath, !path.isEmpty else {
120-
// Populate the whole schema
121-
return schemaHandler(map)
125+
// Retrieve value for path
126+
return valueHandler(map)
122127
}
123128

124129
let pathArray = path.components(separatedBy: ".")
@@ -128,15 +133,15 @@ public class OptimizelyJSON: NSObject {
128133
for (index, key) in pathArray.enumerated() {
129134
guard let value = internalMap[key] else {
130135
self.logger.e(.valueForKeyNotFound(key))
131-
return false
136+
return nil
132137
}
133138
if let dict = value as? [String: Any] {
134139
internalMap = dict
135140
}
136141
if index == lastIndex {
137-
return schemaHandler(value)
142+
return valueHandler(value)
138143
}
139144
}
140-
return false
145+
return nil
141146
}
142147
}

Sources/Utils/LogMessage.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ enum LogMessage {
6767
case eventBatchFailed
6868
case eventSendRetyFailed(_ count: Int)
6969
case failedToConvertMapToString
70-
case failedToAssignValueToSchema
70+
case failedToAssignValue
7171
case valueForKeyNotFound(_ key: String)
7272
}
7373

@@ -126,7 +126,7 @@ extension LogMessage: CustomStringConvertible {
126126
case .eventBatchFailed: message = "Failed to batch events"
127127
case .eventSendRetyFailed(let count): message = "Event dispatch retries failed (\(count)) times"
128128
case .failedToConvertMapToString: message = "Provided map could not be converted to string."
129-
case .failedToAssignValueToSchema: message = "Value for path could not be assigned to provided schema."
129+
case .failedToAssignValue: message = "Value for path could not be assigned to provided type."
130130
case .valueForKeyNotFound(let key): message = "Value for JSON key (\(key)) not found."
131131
}
132132

0 commit comments

Comments
 (0)