/
ImmutableMappable.swift
376 lines (307 loc) · 16.8 KB
/
ImmutableMappable.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
//
// ImmutableMappble.swift
// ObjectMapper
//
// Created by Suyeol Jeon on 23/09/2016.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2018 Tristan Himmelman
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public protocol ImmutableMappable: BaseMappable {
init(map: Map) throws
}
public extension ImmutableMappable {
/// Implement this method to support object -> JSON transform.
func mapping(map: Map) {}
/// Initializes object from a JSON String
init(JSONString: String, context: MapContext? = nil) throws {
self = try Mapper(context: context).map(JSONString: JSONString)
}
/// Initializes object from a JSON Dictionary
init(JSON: [String: Any], context: MapContext? = nil) throws {
self = try Mapper(context: context).map(JSON: JSON)
}
/// Initializes object from a JSONObject
init(JSONObject: Any, context: MapContext? = nil) throws {
self = try Mapper(context: context).map(JSONObject: JSONObject)
}
}
public extension Map {
fileprivate func currentValue(for key: String, nested: Bool? = nil, delimiter: String = ".") -> Any? {
let isNested = nested ?? key.contains(delimiter)
return self[key, nested: isNested, delimiter: delimiter].currentValue
}
// MARK: Basic
/// Returns a value or throws an error.
func value<T>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let value = currentValue as? T else {
throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '\(T.self)'", file: file, function: function, line: line)
}
return value
}
/// Returns a transformed value or throws an error.
func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> Transform.Object {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let value = transform.transformFromJSON(currentValue) else {
throw MapError(key: key, currentValue: currentValue, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line)
}
return value
}
/// Returns a RawRepresentable type or throws an error.
func value<T: RawRepresentable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T {
return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line)
}
/// Returns a RawRepresentable type or throws an error.
func value<T: RawRepresentable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T? {
return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line)
}
/// Returns a `[RawRepresentable]` type or throws an error.
func value<T: RawRepresentable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T] {
return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line)
}
/// Returns a `[RawRepresentable]` type or throws an error.
func value<T: RawRepresentable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T]? {
return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line)
}
// MARK: BaseMappable
/// Returns a `BaseMappable` object or throws an error.
func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let JSONObject = currentValue else {
throw MapError(key: key, currentValue: currentValue, reason: "Found unexpected nil value", file: file, function: function, line: line)
}
return try Mapper<T>(context: context).mapOrFail(JSONObject: JSONObject)
}
/// Returns a `BaseMappable` object boxed in `Optional` or throws an error.
func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T? {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let JSONObject = currentValue else {
throw MapError(key: key, currentValue: currentValue, reason: "Found unexpected nil value", file: file, function: function, line: line)
}
return try Mapper<T>(context: context).mapOrFail(JSONObject: JSONObject)
}
// MARK: [BaseMappable]
/// Returns a `[BaseMappable]` or throws an error.
func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T] {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let jsonArray = currentValue as? [Any] else {
throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line)
}
return try jsonArray.map { JSONObject -> T in
return try Mapper<T>(context: context).mapOrFail(JSONObject: JSONObject)
}
}
/// Returns a `[BaseMappable]` boxed in `Optional` or throws an error.
func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T]? {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let jsonArray = currentValue as? [Any] else {
throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line)
}
return try jsonArray.map { JSONObject -> T in
return try Mapper<T>(context: context).mapOrFail(JSONObject: JSONObject)
}
}
/// Returns a `[BaseMappable]` using transform or throws an error.
func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [Transform.Object] {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let jsonArray = currentValue as? [Any] else {
throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line)
}
return try jsonArray.map { json -> Transform.Object in
guard let object = transform.transformFromJSON(json) else {
throw MapError(key: "\(key)", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line)
}
return object
}
}
// MARK: [String: BaseMappable]
/// Returns a `[String: BaseMappable]` or throws an error.
func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: T] {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let jsonDictionary = currentValue as? [String: Any] else {
throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line)
}
return try jsonDictionary.mapValues { json in
return try Mapper<T>(context: context).mapOrFail(JSONObject: json)
}
}
/// Returns a `[String: BaseMappable]` boxed in `Optional` or throws an error.
func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: T]? {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let jsonDictionary = currentValue as? [String: Any] else {
throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line)
}
var value: [String: T] = [:]
for (key, json) in jsonDictionary {
value[key] = try Mapper<T>(context: context).mapOrFail(JSONObject: json)
}
return value
}
/// Returns a `[String: BaseMappable]` using transform or throws an error.
func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: Transform.Object] {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let jsonDictionary = currentValue as? [String: Any] else {
throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line)
}
return try jsonDictionary.mapValues { json in
guard let object = transform.transformFromJSON(json) else {
throw MapError(key: key, currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line)
}
return object
}
}
/// Returns a `[String: BaseMappable]` using transform or throws an error.
func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [[T]]? {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let json2DArray = currentValue as? [[Any]] else {
throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[[Any]]'", file: file, function: function, line: line)
}
return try json2DArray.map { jsonArray in
try jsonArray.map { jsonObject -> T in
return try Mapper<T>(context: context).mapOrFail(JSONObject: jsonObject)
}
}
}
// MARK: [[BaseMappable]]
/// Returns a `[[BaseMappable]]` or throws an error.
func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [[T]] {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let json2DArray = currentValue as? [[Any]] else {
throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[[Any]]'", file: file, function: function, line: line)
}
return try json2DArray.map { jsonArray in
try jsonArray.map { jsonObject -> T in
return try Mapper<T>(context: context).mapOrFail(JSONObject: jsonObject)
}
}
}
/// Returns a `[[BaseMappable]]` using transform or throws an error.
func value<Transform: TransformType>(_ key: String, nested: Bool? = nil, delimiter: String = ".", using transform: Transform, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [[Transform.Object]] {
let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
guard let json2DArray = currentValue as? [[Any]] else {
throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[[Any]]'",
file: file, function: function, line: line)
}
return try json2DArray.map { jsonArray in
try jsonArray.map { json -> Transform.Object in
guard let object = transform.transformFromJSON(json) else {
throw MapError(key: "\(key)", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line)
}
return object
}
}
}
}
public extension Mapper where N: ImmutableMappable {
func map(JSON: [String: Any]) throws -> N {
return try self.mapOrFail(JSON: JSON)
}
func map(JSONString: String) throws -> N {
return try mapOrFail(JSONString: JSONString)
}
func map(JSONObject: Any) throws -> N {
return try mapOrFail(JSONObject: JSONObject)
}
// MARK: Array mapping functions
func mapArray(JSONArray: [[String: Any]]) throws -> [N] {
#if swift(>=4.1)
return try JSONArray.compactMap(mapOrFail)
#else
return try JSONArray.flatMap(mapOrFail)
#endif
}
func mapArray(JSONString: String) throws -> [N] {
guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else {
throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'")
}
return try mapArray(JSONObject: JSONObject)
}
func mapArray(JSONObject: Any) throws -> [N] {
guard let JSONArray = JSONObject as? [[String: Any]] else {
throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[String: Any]]'")
}
return try mapArray(JSONArray: JSONArray)
}
// MARK: Dictionary mapping functions
func mapDictionary(JSONString: String) throws -> [String: N] {
guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else {
throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'")
}
return try mapDictionary(JSONObject: JSONObject)
}
func mapDictionary(JSONObject: Any?) throws -> [String: N] {
guard let JSON = JSONObject as? [String: [String: Any]] else {
throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''")
}
return try mapDictionary(JSON: JSON)
}
func mapDictionary(JSON: [String: [String: Any]]) throws -> [String: N] {
return try JSON.filterMap(mapOrFail)
}
// MARK: Dictinoary of arrays mapping functions
func mapDictionaryOfArrays(JSONObject: Any?) throws -> [String: [N]] {
guard let JSON = JSONObject as? [String: [[String: Any]]] else {
throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''")
}
return try mapDictionaryOfArrays(JSON: JSON)
}
func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) throws -> [String: [N]] {
return try JSON.filterMap { array -> [N] in
try mapArray(JSONArray: array)
}
}
// MARK: 2 dimentional array mapping functions
func mapArrayOfArrays(JSONObject: Any?) throws -> [[N]] {
guard let JSONArray = JSONObject as? [[[String: Any]]] else {
throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[[String: Any]]]''")
}
return try JSONArray.map(mapArray)
}
}
internal extension Mapper {
func mapOrFail(JSON: [String: Any]) throws -> N {
let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues)
// Check if object is ImmutableMappable, if so use ImmutableMappable protocol for mapping
if let klass = N.self as? ImmutableMappable.Type,
var object = try klass.init(map: map) as? N {
object.mapping(map: map)
return object
}
// If not, map the object the standard way
guard let value = self.map(JSON: JSON) else {
throw MapError(key: nil, currentValue: JSON, reason: "Cannot map to '\(N.self)'")
}
return value
}
func mapOrFail(JSONString: String) throws -> N {
guard let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) else {
throw MapError(key: nil, currentValue: JSONString, reason: "Cannot parse into '[String: Any]'")
}
return try mapOrFail(JSON: JSON)
}
func mapOrFail(JSONObject: Any) throws -> N {
guard let JSON = JSONObject as? [String: Any] else {
throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: Any]'")
}
return try mapOrFail(JSON: JSON)
}
}