forked from JohnSundell/Unbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Unbox.swift
565 lines (463 loc) · 23 KB
/
Unbox.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
/**
* Unbox - the easy to use Swift JSON decoder
*
* For usage, see documentation of the classes/symbols listed in this file, as well
* as the guide available at: github.com/johnsundell/unbox
*
* Copyright (c) 2015 John Sundell. Licensed under the MIT license, as follows:
*
* 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.
*/
import Foundation
/// Type alias defining what type of Dictionary that is Unboxable (valid JSON)
public typealias UnboxableDictionary = [String : AnyObject]
// MARK: - Main Unbox functions
/// Unbox a JSON dictionary into a model `T`, while optionally using a contextual object
public func Unbox<T: Unboxable>(dictionary: UnboxableDictionary, context: Any? = nil) -> T? {
return try? UnboxOrThrow(dictionary, context: context)
}
/// Unbox an array of JSON dictionaries into an array of `T`, while optionally using a contextual object
public func Unbox<T: Unboxable>(dictionaries: [UnboxableDictionary], context: Any? = nil) -> [T]? {
return try? UnboxOrThrow(dictionaries, context: context)
}
/// Unbox binary data into a model `T`, while optionally using a contextual object
public func Unbox<T: Unboxable>(data: NSData, context: Any? = nil) -> T? {
return try? UnboxOrThrow(data, context: context)
}
/// Unbox binary data into an array of `T`, while optionally using a contextual object
public func Unbox<T: Unboxable>(data: NSData, context: Any? = nil) -> [T]? {
return try? UnboxOrThrow(data, context: context)
}
/// Unbox a JSON dictionary into a model `T`, while using a required contextual object
public func Unbox<T: UnboxableWithContext>(dictionary: UnboxableDictionary, context: T.ContextType) -> T? {
return try? UnboxOrThrow(dictionary, context: context)
}
/// Unbox an array of JSON dictionaries into an array of `T`, while using a required contextual object
public func Unbox<T: UnboxableWithContext>(dictionaries: [UnboxableDictionary], context: T.ContextType) -> [T]? {
return try? UnboxOrThrow(dictionaries, context: context)
}
/// Unbox binary data into a model `T`, while using a required contextual object
public func Unbox<T: UnboxableWithContext>(data: NSData, context: T.ContextType) -> T? {
return try? UnboxOrThrow(data, context: context)
}
/// Unbox binary data into an array of `T`, while using a required contextual object
public func Unbox<T: UnboxableWithContext>(data: NSData, context: T.ContextType) -> [T]? {
return try? UnboxOrThrow(data, context: context)
}
// MARK: - Throwing Unbox functions
/// Unbox a JSON dictionary into a model `T`, while optionally using a contextual object. Throws `UnboxError`.
public func UnboxOrThrow<T: Unboxable>(dictionary: UnboxableDictionary, context: Any? = nil) throws -> T {
return try Unboxer(dictionary: dictionary, context: context).performUnboxing()
}
/// Unbox an array of JSON dictionaries into an array of `T`, while optionally using a contextual object. Throws `UnboxError`.
public func UnboxOrThrow<T: Unboxable>(dictionaries: [UnboxableDictionary], context: Any? = nil) throws -> [T] {
return try dictionaries.map({
try UnboxOrThrow($0, context: context)
})
}
/// Unbox binary data into a model `T`, while optionally using a contextual object. Throws `UnboxError`.
public func UnboxOrThrow<T: Unboxable>(data: NSData, context: Any? = nil) throws -> T {
return try Unboxer.unboxerFromData(data, context: context).performUnboxing()
}
/// Unbox binary data into an array of `T`, while optionally using a contextual object. Throws `UnboxError`.
public func UnboxOrThrow<T: Unboxable>(data: NSData, context: Any? = nil) throws -> [T] {
return try Unboxer.unboxersFromData(data, context: context).map({
return try $0.performUnboxing()
})
}
/// Unbox a JSON dictionary into a model `T`, while using a required contextual object. Throws `UnboxError`.
public func UnboxOrThrow<T: UnboxableWithContext>(dictionary: UnboxableDictionary, context: T.ContextType) throws -> T {
return try Unboxer(dictionary: dictionary, context: context).performUnboxingWithContext(context)
}
/// Unbox an array of JSON dictionaries into an array of `T`, while using a required contextual object. Throws `UnboxError`.
public func UnboxOrThrow<T: UnboxableWithContext>(dictionaries: [UnboxableDictionary], context: T.ContextType) throws -> [T] {
return try dictionaries.map({
try UnboxOrThrow($0, context: context)
})
}
/// Unbox binary data into a model `T`, while using a required contextual object. Throws `UnboxError`.
public func UnboxOrThrow<T: UnboxableWithContext>(data: NSData, context: T.ContextType) throws -> T {
return try Unboxer.unboxerFromData(data, context: context).performUnboxingWithContext(context)
}
/// Unbox binary data into an array of `T`, while using a required contextual object. Throws `UnboxError`.
public func UnboxOrThrow<T: UnboxableWithContext>(data: NSData, context: T.ContextType) throws -> [T] {
return try Unboxer.unboxersFromData(data, context: context).map({
return try $0.performUnboxingWithContext(context)
})
}
// MARK: - Error type
/// Enum describing errors that can occur during unboxing. Use the throwing functions to receive any errors.
public enum UnboxError: ErrorType, CustomStringConvertible {
public var description: String {
let baseDescription = "[Unbox error] "
switch self {
case .MissingKey(let key):
return baseDescription + "Missing key (\(key))"
case .InvalidValue(let key, let valueDescription):
return baseDescription + "Invalid value (\(valueDescription)) for key (\(key))"
case .InvalidData:
return "Invalid data"
}
}
/// Thrown when a required key was missing in an unboxed dictionary. Contains the missing key.
case MissingKey(String)
/// Thrown when a required key contained an invalid value in an unboxed dictionary. Contains the invalid
/// key and a description of the invalid data.
case InvalidValue(String, String)
/// Thrown when a piece of data (NSData) could not be unboxed because it was considered invalid
case InvalidData
}
// MARK: - Protocols
/// Protocol used to declare a model as being Unboxable, for use with the Unbox() function
public protocol Unboxable {
/// Initialize an instance of this model by unboxing a dictionary using an Unboxer
init(unboxer: Unboxer)
}
/// Protocol used to declare a model as being Unboxable with a certain context, for use with the Unbox(context:) function
public protocol UnboxableWithContext {
/// The type of the contextual object that this model requires when unboxed
typealias ContextType
/// Initialize an instance of this model by unboxing a dictionary & using a context
init(unboxer: Unboxer, context: ContextType)
}
/// Protocol that types that can be used in an unboxing process must conform to
public protocol UnboxCompatibleType {
/// The value to use for required properties if unboxing failed. Typically a dummy value.
static func unboxFallbackValue() -> Self
}
/// Protocol used to enable a raw type for Unboxing. See default implementations further down.
public protocol UnboxableRawType: UnboxCompatibleType {}
/// Protocol used to enable an enum to be directly unboxable
public protocol UnboxableEnum: RawRepresentable, UnboxCompatibleType {}
/// Protocol used to enable any type as being unboxable, by transforming a raw value
public protocol UnboxableByTransform: UnboxCompatibleType {
/// The type of raw value that this type can be transformed from
typealias UnboxRawValueType: UnboxableRawType
/// Attempt to transform a raw unboxed value into an instance of this type
static func transformUnboxedValue(unboxedValue: UnboxRawValueType) -> Self?
}
// MARK: - Extensions
/// Extension making Bool an Unboxable raw type
extension Bool: UnboxableRawType {
public static func unboxFallbackValue() -> Bool {
return false
}
}
/// Extension making Int an Unboxable raw type
extension Int: UnboxableRawType {
public static func unboxFallbackValue() -> Int {
return 0
}
}
/// Extension making Double an Unboxable raw type
extension Double: UnboxableRawType {
public static func unboxFallbackValue() -> Double {
return 0
}
}
/// Extension making Float an Unboxable raw type
extension Float: UnboxableRawType {
public static func unboxFallbackValue() -> Float {
return 0
}
}
/// Extension making String an Unboxable raw type
extension String: UnboxableRawType {
public static func unboxFallbackValue() -> String {
return ""
}
}
/// Extension making NSURL Unboxable by transform
extension NSURL: UnboxableByTransform {
public typealias UnboxRawValueType = String
public static func transformUnboxedValue(rawValue: String) -> Self? {
return self.init(string: rawValue)
}
public static func unboxFallbackValue() -> Self {
return self.init()
}
}
// MARK: - Unboxer
/**
* Class used to Unbox (decode) values from a dictionary
*
* For each supported type, simply call `unbox(string)` (where `string` is either a key or a key path in the dictionary
* that is being unboxed) - and the correct type will be returned. If a required (non-optional) value couldn't be
* unboxed, the Unboxer will be marked as failed, and a `nil` value will be returned from the `Unbox()` function that
* triggered the Unboxer.
*
* An Unboxer may also be manually failed, by using the `failForKey()` or `failForInvalidValue(forKey:)` APIs.
*/
public class Unboxer {
/// All keys contained within the underlying JSON data that is being unboxed
public var allKeys: [String] { return Array(self.dictionary.keys) }
/// Whether the Unboxer has failed, and a `nil` value will be returned from the `Unbox()` function that triggered it.
public var hasFailed: Bool { return self.failureInfo != nil }
/// Any contextual object that was supplied when unboxing was started
public let context: Any?
private var failureInfo: (key: String, value: Any?)?
private let dictionary: UnboxableDictionary
// MARK: - Private initializer
private init(dictionary: UnboxableDictionary, context: Any?) {
self.dictionary = dictionary
self.context = context
}
// MARK: - Public API
/// Unbox a required raw type
public func unbox<T: UnboxableRawType>(key: String) -> T {
return UnboxValueResolver<T>(self).resolveRequiredValueForKey(key, fallbackValue: T.unboxFallbackValue())
}
/// Unbox an optional raw type
public func unbox<T: UnboxableRawType>(key: String) -> T? {
return UnboxValueResolver<T>(self).resolveOptionalValueForKey(key)
}
/// Unbox a required Array
public func unbox<T>(key: String) -> [T] {
return UnboxValueResolver<[T]>(self).resolveRequiredValueForKey(key, fallbackValue: [])
}
/// Unbox an optional Array
public func unbox<T>(key: String) -> [T]? {
return UnboxValueResolver<[T]>(self).resolveOptionalValueForKey(key)
}
/// Unbox a required Dictionary
public func unbox<T>(key: String) -> [String : T] {
return UnboxValueResolver<[String : T]>(self).resolveRequiredValueForKey(key, fallbackValue: [:])
}
/// Unbox an optional Dictionary
public func unbox<T>(key: String) -> [String : T]? {
return UnboxValueResolver<[String : T]>(self).resolveOptionalValueForKey(key)
}
/// Unbox a required enum value
public func unbox<T: UnboxableEnum>(key: String) -> T {
return UnboxValueResolver<T.RawValue>(self).resolveRequiredValueForKey(key, fallbackValue: T.unboxFallbackValue(), transform: {
return T(rawValue: $0)
})
}
/// Unbox an optional enum value
public func unbox<T: UnboxableEnum>(key: String) -> T? {
return UnboxValueResolver<T.RawValue>(self).resolveOptionalValueForKey(key, transform: {
return T(rawValue: $0)
})
}
/// Unbox a required nested Unboxable, by unboxing a Dictionary and then using a transform
public func unbox<T: Unboxable>(key: String) -> T {
return UnboxValueResolver<UnboxableDictionary>(self).resolveRequiredValueForKey(key, fallbackValue: T.unboxFallbackValue(), transform: {
return Unbox($0, context: self.context)
})
}
/// Unbox an optional nested Unboxable, by unboxing a Dictionary and then using a transform
public func unbox<T: Unboxable>(key: String) -> T? {
return UnboxValueResolver<UnboxableDictionary>(self).resolveOptionalValueForKey(key, transform: {
return Unbox($0, context: self.context)
})
}
/// Unbox a required Array of nested Unboxables, by unboxing an Array of Dictionaries and then using a transform
public func unbox<T: Unboxable>(key: String) -> [T] {
return UnboxValueResolver<[UnboxableDictionary]>(self).resolveRequiredValueForKey(key, fallbackValue: [], transform: {
return Unbox($0, context: self.context)
})
}
/// Unbox an optional Array of nested Unboxables, by unboxing an Array of Dictionaries and then using a transform
public func unbox<T: Unboxable>(key: String) -> [T]? {
return UnboxValueResolver<[UnboxableDictionary]>(self).resolveOptionalValueForKey(key, transform: {
return Unbox($0, context: self.context)
})
}
/// Unbox a required Dictionary of nested Unboxables, by unboxing an Dictionary of Dictionaries and then using a transform
public func unbox<T: Unboxable>(key: String) -> [String : T] {
return UnboxValueResolver<[String : UnboxableDictionary]>(self).resolveDictionaryValuesForKey(key, required: true, valueTransform: {
return Unbox($0, context: self.context)
})
}
/// Unbox an optional Dictionary of nested Unboxables, by unboxing an Dictionary of Dictionaries and then using a transform
public func unbox<T: Unboxable>(key: String) -> [String : T]? {
return UnboxValueResolver<[String : UnboxableDictionary]>(self).resolveDictionaryValuesForKey(key, required: false, valueTransform: {
return Unbox($0, context: self.context)
})
}
/// Unbox a required nested UnboxableWithContext type
public func unbox<T: UnboxableWithContext>(key: String, context: T.ContextType) -> T {
return UnboxValueResolver<UnboxableDictionary>(self).resolveRequiredValueForKey(key, fallbackValue: T.unboxFallbackValueWithContext(context), transform: {
return Unbox($0, context: context)
})
}
/// Unbox an optional nested UnboxableWithContext type
public func unbox<T: UnboxableWithContext>(key: String, context: T.ContextType) -> T? {
return UnboxValueResolver<UnboxableDictionary>(self).resolveOptionalValueForKey(key, transform: {
return Unbox($0, context: context)
})
}
/// Unbox a required Array of nested UnboxableWithContext types, by unboxing an Array of Dictionaries and then using a transform
public func unbox<T: UnboxableWithContext>(key: String, context: T.ContextType) -> [T] {
return UnboxValueResolver<[UnboxableDictionary]>(self).resolveRequiredValueForKey(key, fallbackValue: [], transform: {
return Unbox($0, context: context)
})
}
/// Unbox an optional Array of nested UnboxableWithContext types, by unboxing an Array of Dictionaries and then using a transform
public func unbox<T: UnboxableWithContext>(key: String, context: T.ContextType) -> [T]? {
return UnboxValueResolver<[UnboxableDictionary]>(self).resolveOptionalValueForKey(key, transform: {
return Unbox($0, context: context)
})
}
/// Unbox a required value that can be transformed into its final form
public func unbox<T: UnboxableByTransform>(key: String) -> T {
return UnboxValueResolver<T.UnboxRawValueType>(self).resolveRequiredValueForKey(key, fallbackValue: T.unboxFallbackValue(), transform: {
return T.transformUnboxedValue($0)
})
}
/// Unbox an optional value that can be transformed into its final form
public func unbox<T: UnboxableByTransform>(key: String) -> T? {
return UnboxValueResolver<T.UnboxRawValueType>(self).resolveOptionalValueForKey(key, transform: {
return T.transformUnboxedValue($0)
})
}
/// Make this Unboxer to fail for a certain key. This will cause the `Unbox()` function that triggered this Unboxer to return `nil`.
public func failForKey(key: String) {
self.failForInvalidValue(nil, forKey: key)
}
/// Make this Unboxer to fail for a certain key and invalid value. This will cause the `Unbox()` function that triggered this Unboxer to return `nil`.
public func failForInvalidValue(invalidValue: Any?, forKey key: String) {
self.failureInfo = (key, invalidValue)
}
}
// MARK: - UnboxValueResolver
private class UnboxValueResolver<T> {
let unboxer: Unboxer
init(_ unboxer: Unboxer) {
self.unboxer = unboxer
}
func resolveRequiredValueForKey(key: String, @autoclosure fallbackValue: () -> T) -> T {
return self.resolveRequiredValueForKey(key, fallbackValue: fallbackValue, transform: {
return $0
})
}
func resolveRequiredValueForKey<R>(key: String, @autoclosure fallbackValue: () -> R, transform: T -> R?) -> R {
if let value = self.resolveOptionalValueForKey(key, transform: transform) {
return value
}
self.unboxer.failForInvalidValue(self.unboxer.dictionary[key], forKey: key)
return fallbackValue()
}
func resolveOptionalValueForKey(key: String) -> T? {
return self.resolveOptionalValueForKey(key, transform: {
return $0
})
}
func resolveOptionalValueForKey<R>(var key: String, transform: T -> R?) -> R? {
var dictionary = self.unboxer.dictionary
if key.containsString(".") {
let components = key.componentsSeparatedByString(".")
for var i = 0; i < components.count; i++ {
let keyPathComponent = components[i]
if i == components.count - 1 {
key = keyPathComponent
} else if let nestedDictionary = dictionary[keyPathComponent] as? UnboxableDictionary {
dictionary = nestedDictionary
} else {
return nil
}
}
}
if let value = dictionary[key] as? T {
if let transformed = transform(value) {
return transformed
}
}
return nil
}
}
extension UnboxValueResolver where T: CollectionType, T: DictionaryLiteralConvertible, T.Key: Hashable, T.Generator == DictionaryGenerator<T.Key, T.Value> {
func resolveDictionaryValuesForKey<K, V>(key: String, required: Bool, keyTransform: (T.Key -> K?)? = nil, valueTransform: T.Value -> V?) -> [K : V] {
if let unboxedDictionary = self.resolveOptionalValueForKey(key) {
var transformedDictionary = [K : V]()
for (unboxedKey, unboxedValue) in unboxedDictionary {
let transformedKey: K?
if let keyTransform = keyTransform {
transformedKey = keyTransform(unboxedKey)
} else {
transformedKey = unboxedKey as? K
}
if let transformedKey = transformedKey, transformedValue = valueTransform(unboxedValue) {
transformedDictionary[transformedKey] = transformedValue
} else if required {
self.unboxer.failForInvalidValue(unboxedValue, forKey: key)
return [:]
}
}
return transformedDictionary
} else if required {
self.unboxer.failForInvalidValue(self.unboxer.dictionary[key], forKey: key)
}
return [:]
}
}
// MARK: - Private extensions
private extension Unboxable {
static func unboxFallbackValue() -> Self {
return self.init(unboxer: Unboxer(dictionary: [:], context: nil))
}
}
private extension UnboxableWithContext {
static func unboxFallbackValueWithContext(context: ContextType) -> Self {
return self.init(unboxer: Unboxer(dictionary: [:], context: context), context: context)
}
}
private extension Unboxer {
static func unboxerFromData(data: NSData, context: Any?) throws -> Unboxer {
do {
guard let dictionary = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? UnboxableDictionary else {
throw UnboxError.InvalidData
}
return Unboxer(dictionary: dictionary, context: context)
} catch {
throw UnboxError.InvalidData
}
}
static func unboxersFromData(data: NSData, context: Any?) throws -> [Unboxer] {
do {
guard let array = try NSJSONSerialization.JSONObjectWithData(data, options: [.AllowFragments]) as? [UnboxableDictionary] else {
throw UnboxError.InvalidData
}
return array.map({
return Unboxer(dictionary: $0, context: context)
})
} catch {
throw UnboxError.InvalidData
}
}
func performUnboxing<T: Unboxable>() throws -> T {
let unboxed = T(unboxer: self)
try self.throwIfFailed()
return unboxed
}
func performUnboxingWithContext<T: UnboxableWithContext>(context: T.ContextType) throws -> T {
let unboxed = T(unboxer: self, context: context)
try self.throwIfFailed()
return unboxed
}
func throwIfFailed() throws {
guard let failureInfo = self.failureInfo else {
return
}
if let failedValue: Any = failureInfo.value {
throw UnboxError.InvalidValue(failureInfo.key, "\(failedValue)")
}
throw UnboxError.MissingKey(failureInfo.key)
}
}