EVReflectable.swift 23.4 KB
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 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
//
//  EVReflectable.swift
//  EVReflection
//
//  Created by Edwin Vermeer on 27/10/2016.
//  Copyright © 2016 evict. All rights reserved.
//

import Foundation

// MARK: - Protocol with the overridable functions. All functionality is added to this in the extension below.
public protocol EVReflectable: class, NSObjectProtocol  {
    /**
     By default there is no aditional validation. Override this function to add your own class level validation rules
     
     - parameter dict: The dictionary with keys where the initialisation is called with
     */
    func initValidation(_ dict: NSDictionary)
    
    /**
     Override this method when you want custom property mapping.
     
     This method is in EVObject and not in extension of NSObject because a functions from extensions cannot be overwritten yet
     
     - returns: Return an array with value pairs of the object property name and json key name.
     */
    func propertyMapping() -> [(keyInObject: String?, keyInResource: String?)]
    
    /**
     Override this method when you want custom property value conversion
     
     This method is in EVObject and not in extension of NSObject because a functions from extensions cannot be overwritten yet
     
     - returns: Returns an array where each item is a combination of the folowing 3 values: A string for the property name where the custom conversion is for, a setter function and a getter function.
     */
    func propertyConverters() -> [(key: String, decodeConverter: ((Any?)->()), encodeConverter: (() -> Any?))]
    
    /**
     This is a general functon where you can filter for specific values (like nil or empty string) when creating a dictionary
     
     - parameter value:  The value that we will test
     - parameter key: The key for the value
     
     - returns: True if the value needs to be ignored.
     */
    func skipPropertyValue(_ value: Any, key: String) -> Bool
    
    /**
     You can add general value decoding to an object when you implement this function. You can for instance use it to base64 decode, url decode, html decode, unicode, etc.
     
     - parameter value:  The value that we will be decoded
     - parameter key: The key for the value
     
     - returns: The decoded value
     */
    func decodePropertyValue(value: Any, key: String) -> Any?

    /**
     You can add general value encoding to an object when you implement this function. You can for instance use it to base64 encode, url encode, html encode, unicode, etc.
     
     - parameter value:  The value that we will be encoded
     - parameter key: The key for the value
     
     - returns: The encoded value.
     */
    func encodePropertyValue(value: Any, key: String) -> Any
    
    /**
     Get the type of this object.
     
     - parameter dict: The dictionary for the specific type
     
     - returns: The specific type
     */
    func getType(_ dict: NSDictionary) -> EVReflectable
    
    /**
     When a property is declared as a base type for multiple inherited classes, then this function will let you pick the right specific type based on the suplied dictionary.
     
     - parameter dict: The dictionary for the specific type
     
     - returns: The specific type
     */
    func getSpecificType(_ dict: NSDictionary) -> EVReflectable?
    
    /**
     Return a custom object for the object
     
     - returns: The custom object that will be parsed (single value, dictionary or array)
     */
    func customConverter() -> AnyObject?

/*
    /**
     Declaration for Equatable ==
     
     - parameter lhs: The object at the left side of the ==
     - parameter rhs: The object at the right side of the ==
     
     - returns: True if the objects are the same, otherwise false.
     */
    static func ==(lhs: EVReflectable, rhs: EVReflectable) -> Bool
    
    /**
     Delclaration for Equatable !=
     
     - parameter lhs: The object at the left side of the ==
     - parameter rhs: The object at the right side of the ==
     
     - returns: False if the objects are the the same, otherwise true.
     */
    static func !=(lhs: EVReflectable, rhs: EVReflectable) -> Bool
*/
    /**
     Protocol container property for the reflection statusses
     */
    var evReflectionStatuses: [(DeserializationStatus, String)] { get set }
}


// MARK: - extending EVReflectable with the initialisation functions (which need NSObject)

var EVReflectableStatusesObjectKey = "EVReflectableStatuses"
extension EVReflectable where Self: NSObject {
    /**
     Trick for storing a property in a protocol only
     */
    public var evReflectionStatuses: [(DeserializationStatus, String)] {
        get {
            var statuses: [(DeserializationStatus, String)]? = objc_getAssociatedObject(self, &EVReflectableStatusesObjectKey) as? [(DeserializationStatus, String)]
            if let statuses = statuses {
                return statuses
            } else {
                statuses = [(DeserializationStatus, String)]()
                objc_setAssociatedObject(self, &EVReflectableStatusesObjectKey, statuses, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
                return statuses!
            }
        }
        set {
            objc_setAssociatedObject(self, &EVReflectableStatusesObjectKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
        }
    }
    
    
    /**
     init for creating an object whith the property values of a dictionary.
     
     - parameter dictionary: The dictionary that will be used to create this object
     - parameter conversionOptions: Option set for the various conversion options.
     */
    public init(dictionary: NSDictionary, conversionOptions: ConversionOptions = .DefaultDeserialize, forKeyPath: String? = nil) {
        self.init()
        if let v = self as? EVCustomReflectable {
            let _ = v.constructWith(value: dictionary)
        } else {
            EVReflection.setPropertiesfromDictionary(dictionary, anyObject: self, conversionOptions: conversionOptions, forKeyPath: forKeyPath)
        }
    }
    
    /**
     init for creating an object whith the contents of a json string.
     
     - parameter json: The json string that will be used to create this object
     - parameter conversionOptions: Option set for the various conversion options.
     */
    public init(json: String?, conversionOptions: ConversionOptions = .DefaultDeserialize, forKeyPath: String? = nil) {
        self.init()
        let dictionary = EVReflection.dictionaryFromJson(json)
        if let v = self as? EVCustomReflectable {
            let _ = v.constructWith(value: dictionary)
        } else {
            EVReflection.setPropertiesfromDictionary(dictionary, anyObject: self, conversionOptions: conversionOptions, forKeyPath: forKeyPath)
        }
    }
    
    /**
     init for creating an object whith the property values of json Data.
     
     - parameter dictionary: The dictionary that will be used to create this object
     - parameter conversionOptions: Option set for the various conversion options.
     */
    public init(data: Data, conversionOptions: ConversionOptions = .DefaultDeserialize, forKeyPath: String? = nil) {
        self.init()
        let dictionary: NSDictionary = (((try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary))  ?? NSDictionary())!
        if let v = self as? EVCustomReflectable {
            let _ = v.constructWith(value: dictionary)
        } else {
            EVReflection.setPropertiesfromDictionary(dictionary, anyObject: self, conversionOptions: conversionOptions, forKeyPath: forKeyPath)
        }
    }
    
    
    /**
     Initialize this object from an archived file from the temp directory
     
     - parameter fileNameInTemp: The filename
     - parameter conversionOptions: Option set for the various conversion options.
     */
    public init(fileNameInTemp: String, conversionOptions: ConversionOptions = .DefaultNSCoding) {
        self.init()
        let filePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(fileNameInTemp)
        if let temp = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? EVReflectable {
            if let v = self as? EVCustomReflectable {
                let dictionary = temp.toDictionary(conversionOptions)
                let _ = v.constructWith(value: dictionary)
            } else {
                EVReflection.setPropertiesfromDictionary( temp.toDictionary(conversionOptions), anyObject: self, conversionOptions: conversionOptions)
            }
        }
    }
    
    /**
     Initialize this object from an archived file from the documents directory
     
     - parameter fileNameInDocuments: The filename
     - parameter conversionOptions: Option set for the various conversion options.
     */
    public init(fileNameInDocuments: String, conversionOptions: ConversionOptions = .DefaultNSCoding) {
        self.init()
        let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(fileNameInDocuments)
        if let temp = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? EVReflectable {
            if let v = self as? EVCustomReflectable {
                let dictionary = temp.toDictionary(conversionOptions)
                let _ = v.constructWith(value: dictionary)
            } else {
                EVReflection.setPropertiesfromDictionary( temp.toDictionary(conversionOptions), anyObject: self, conversionOptions: conversionOptions)
            }
        }
    }
    
    /**
     init for creating an object whith the property values of an other object.
     
     - parameter usingValuesFrom: The object of whicht the values will be used to create this object
     - parameter conversionOptions: Option set for the various conversion options.
     */
    public init(usingValuesFrom: EVReflectable, conversionOptions: ConversionOptions = .None) {
        self.init()
        let dict = usingValuesFrom.toDictionary()
        if let v = self as? EVCustomReflectable {
            let _ = v.constructWith(value: dict)
        } else {
            EVReflection.setPropertiesfromDictionary(dict, anyObject: self, conversionOptions: conversionOptions)
        }
        
    }
    
    /**
     Returns the hashvalue of this object
     
     - returns: The hashvalue of this object
     */
    public var hashValue: Int {
        get {
            return Int(EVReflection.hashValue(self))
        }
    }
    
    /**
     Function for returning the hash for the NSObject based functionality
     
     - returns: The hashvalue of this object
     */
    public var hash: Int {
        get {
            return self.hashValue
        }
    }
    
}


// MARK: - extending EVReflectable with most of EVReflection functionality


extension EVReflectable {
    /**
     Implementation for Equatable ==
     
     - parameter lhs: The object at the left side of the ==
     - parameter rhs: The object at the right side of the ==
     
     - returns: True if the objects are the same, otherwise false.
     */
    static public func == (lhs: EVReflectable, rhs: EVReflectable) -> Bool {
        if let lhso = lhs as? NSObject, let rhso = rhs as? NSObject {
            return EVReflection.areEqual(lhso, rhs: rhso)
        }
        return lhs.isEqual(rhs)
    }
    
    /**
     Implementation for Equatable !=
     
     - parameter lhs: The object at the left side of the ==
     - parameter rhs: The object at the right side of the ==
     
     - returns: False if the objects are the the same, otherwise true.
     */
    static public func != (lhs: EVReflectable, rhs: EVReflectable) -> Bool {
        if let lhso = lhs as? NSObject, let rhso = rhs as? NSObject {
            return !EVReflection.areEqual(lhso, rhs: rhso)
        }
        return !lhs.isEqual(rhs)
    }
    
    // MARK: - extending the base implementation for the overridable functions
    
    
    /**
     By default there is no aditional validation. Override this function to add your own class level validation rules
     
     - parameter dict: The dictionary with keys where the initialisation is called with
     */
    public func initValidation(_ dict: NSDictionary) {
    }
    
    /**
     Override this method when you want custom property mapping.
     
     This method is in EVObject and not in extension of NSObject because a functions from extensions cannot be overwritten yet
     
     - returns: Return an array with value pairs of the object property name and json key name.
     */
    public func propertyMapping() -> [(keyInObject: String?, keyInResource: String?)] {
        return []
    }
    
    /**
     Override this method when you want custom property value conversion
     
     This method is in EVObject and not in extension of NSObject because a functions from extensions cannot be overwritten yet
     
     - returns: Returns an array where each item is a combination of the folowing 3 values: A string for the property name where the custom conversion is for, a setter function and a getter function.
     */
    public func propertyConverters() -> [(key: String, decodeConverter: ((Any?)->()), encodeConverter: (() -> Any?))] {
        return []
    }
    
    /**
     This is a general functon where you can filter for specific values (like nil or empty string) when creating a dictionary
     
     - parameter value:  The value that we will test
     - parameter key: The key for the value
     
     - returns: True if the value needs to be ignored.
     */
    public func skipPropertyValue(_ value: Any, key: String) -> Bool {
        return false
    }
    
    /**
     You can add general value decoding to an object when you implement this function. You can for instance use it to base64 decode, url decode, html decode, unicode, etc.
     
     - parameter value:  The value that we will be decoded
     - parameter key: The key for the value
     
     - returns: The decoded value
     */
    public func decodePropertyValue(value: Any, key: String) -> Any? {
        return value
    }
    
    /**
     You can add general value encoding to an object when you implement this function. You can for instance use it to base64 encode, url encode, html encode, unicode, etc.
     
     - parameter value:  The value that we will be encoded
     - parameter key: The key for the value
     
     - returns: The encoded value.
     */
    public func encodePropertyValue(value: Any, key: String) -> Any {
        return value
    }
    
    /**
     Return a custom object for the object
     
     - returns: The custom object that will be parsed (single value, dictionary or array)
     */
    public func customConverter() -> AnyObject? {
        return nil
    }
    
    /**
     Get the type of this object
     
     - parameter dict: The dictionary for the specific type
     
     - returns: The specific type
     */
    public func getType(_ dict: NSDictionary) -> EVReflectable {
        return self
    }
    
    /**
     When a property is declared as a base type for multiple inherited classes, then this function will let you pick the right specific type based on the suplied dictionary.
     
     - parameter dict: The dictionary for the specific type
     
     - returns: The specific type
     */
    public func getSpecificType(_ dict: NSDictionary) -> EVReflectable? {
        return nil
    }
    
    // MARK: - extension methods
    
    
    /**
     Save this object to a file in the temp directory
     
     - parameter fileName: The filename
     
     - returns: Nothing
     */
    @discardableResult
    public func saveToTemp(_ fileName: String) -> Bool {
        let filePath = (NSTemporaryDirectory() as NSString).appendingPathComponent(fileName)
        return NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
    }
    
    
    
    #if os(tvOS)
    // Save to documents folder is not supported on tvOS
    #else
    /**
     Save this object to a file in the documents directory
     
     - parameter fileName: The filename
     
     - returns: true if successfull
     */
    @discardableResult
    public func saveToDocuments(_ fileName: String) -> Bool {
        let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(fileName)
        return NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
    }
    #endif
    
    
    /**
     Returns the dictionary representation of this object.
     
     - parameter conversionOptions: Option set for the various conversion options.
     
     - returns: The dictionary
     */
    public func toDictionary(_ conversionOptions: ConversionOptions = .DefaultSerialize) -> NSDictionary {
        if let obj = self as? NSObject {
            let (reflected, _) = EVReflection.toDictionary(obj, conversionOptions: conversionOptions)
            return reflected
        }
        evPrint(.ShouldExtendNSObject, "ERROR: You should only extend object with EVReflectable that are derived from NSObject!")
        return NSDictionary()
    }
    
    /**
     Convert this object to a json string
     
     - parameter conversionOptions: Option set for the various conversion options.
     
     - returns: The json string
     */
    public func toJsonString(_ conversionOptions: ConversionOptions = .DefaultSerialize, prettyPrinted: Bool = false) -> String {
        let data = self.toJsonData(conversionOptions, prettyPrinted: prettyPrinted)
        return String(data: data, encoding: .utf8) ?? "{}"
    }
    
    /**
     Convert this object to a json Data
     
     - parameter conversionOptions: Option set for the various conversion options.
     
     - returns: The json Data
     */
    public func toJsonData(_ conversionOptions: ConversionOptions = .DefaultSerialize, prettyPrinted: Bool = false) -> Data {
        var dict: NSDictionary
        
        // Custom or standard toDictionary
        if let v = self as? EVCustomReflectable {
            dict = v.toCodableValue() as? NSDictionary ?? NSDictionary()
        } else {
            dict = self.toDictionary(conversionOptions)
        }
        
        if let v = self as? NSObject {
            dict = EVReflection.convertDictionaryForJsonSerialization(dict, theObject: v)
        }
        
        do {
            if prettyPrinted {
                return try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
            }
            return try JSONSerialization.data(withJSONObject: dict, options: [])
        } catch { }
        return Data()
    }
    
    
    /**
     method for instantiating an array from a json string.
     
     - parameter json: The json string
     - parameter conversionOptions: Option set for the various conversion options.
     
     - returns: An array of objects
     */
    public static func arrayFromJson<T>(_ json: String?, conversionOptions: ConversionOptions = .DefaultDeserialize) -> [T] where T:NSObject {
        return EVReflection.arrayFromJson(type: T(), json: json, conversionOptions: conversionOptions)
    }
    
    /**
     Auto map an opbject to an object of an other type.
     Properties with the same name will be mapped automattically.
     Automattic cammpelCase, PascalCase, snake_case conversion
     Supports propperty mapping and conversion when using EVReflectable as a protocol
     
     - parameter conversionOptions: Option set for the various conversion options.
     
     - returns: The targe object with the mapped values
     */
    public func mapObjectTo<T>(_ conversionOptions: ConversionOptions = .DefaultDeserialize) -> T where T:NSObject {
        let nsobjectype: NSObject.Type = T.self as NSObject.Type
        let nsobject: NSObject = nsobjectype.init()
        let dict = self.toDictionary()
        let result = EVReflection.setPropertiesfromDictionary(dict, anyObject: nsobject, conversionOptions: conversionOptions)
        return result as? T ?? T()
    }
    
    /**
     Get the type for a given property name or `nil` if there aren't any properties matching said name.
     
     - parameter propertyName: The property name
     
     - returns: The type for the property
     */
    public func typeForKey(_ propertyName: String) -> Any.Type? {
        let mirror = Mirror(reflecting: self)
        return typeForKey(propertyName, mirror: mirror)
    }
    
    /**
     get the type of a property
     
     - parameter propertyName: The property key
     - parameter mirror:       The mirror of this object
     
     - returns: The type of the property
     */
    fileprivate func typeForKey(_ propertyName: String, mirror: Mirror) -> Any.Type? {
        for (label, value) in mirror.children {
            if propertyName == label {
                return Mirror(reflecting: value).subjectType
            }
        }
        
        guard let superclassMirror = mirror.superclassMirror else {
            return nil
        }
        
        return typeForKey(propertyName, mirror: superclassMirror)
    }
    
    
    /**
     Convert a Swift dictionary to a NSDictionary.
     
     - parameter key:  Key of the property that is the dictionary. Can be used when overriding this function
     - parameter dict: The Swift dictionary
     
     - returns: The dictionary converted to a NSDictionary
     */
    public func convertDictionary(_ key: String, dict: Any) -> NSDictionary {
        let returnDict = NSMutableDictionary()
        for (key, value) in dict as? NSDictionary ?? NSDictionary() {
            returnDict[key as? String ?? ""] = value
        }
        return returnDict
    }
    
    
    // MARK: - extending serialization status functions
    
    
    /**
     Validation function that you will probably call from the initValidation function. This function will make sure
     the passed on keys are not in the dictionary used for initialisation.
     The result of this validation is stored in evReflectionStatus.
     
     - parameter keys: The fields that may not be in the dictionary (like an error key)
     - parameter dict: The dictionary that is passed on from the initValidation function
     */
    public func initMayNotContainKeys(_ keys: [String], dict: NSDictionary) {
        for key in keys {
            if dict[key] != nil {
                addStatusMessage(.IncorrectKey, message: "Invalid key: \(key)")
            }
        }
    }
    
    /**
     Validation function that you will probably call from the initValidation function. This function will make sure
     the passed on keys are in the dictionary used for initialisation.
     The result of this validation is stored in evReflectionStatus.
     
     - parameter keys: The fields that may not be in the dictionary (like an error key)
     - parameter dict: The dictionary that is passed on from the initValidation function
     */
    public func initMustContainKeys(_ keys: [String], dict: NSDictionary) {
        for key in keys {
            if dict[key] == nil {
                addStatusMessage(.MissingKey, message: "Missing key: \(key)")
            }
        }
    }
    /**
     Return a merged status out of the status array
     
     - returns: the deserialization status for the object
     */
    public func evReflectionStatus() -> DeserializationStatus {
        var status: DeserializationStatus = .None
        for (s, _) in self.evReflectionStatuses {
            status = [status, s]
        }
        return status
    }
    
    /**
     function for adding a new status message to the evReflectionStatus array
     
     - parameter type:    A string to specify the message type
     - parameter message: The message for the status.
     */
    public func addStatusMessage(_ type: DeserializationStatus, message: String) {
        self.evReflectionStatuses.append((type, message))
    }    
}