You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

321 lines
14 KiB

  1. //
  2. // ImmutableMappble.swift
  3. // ObjectMapper
  4. //
  5. // Created by Suyeol Jeon on 23/09/2016.
  6. //
  7. // The MIT License (MIT)
  8. //
  9. // Copyright (c) 2014-2016 Hearst
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining a copy
  12. // of this software and associated documentation files (the "Software"), to deal
  13. // in the Software without restriction, including without limitation the rights
  14. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. // copies of the Software, and to permit persons to whom the Software is
  16. // furnished to do so, subject to the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be included in
  19. // all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. // THE SOFTWARE.
  28. public protocol ImmutableMappable: BaseMappable {
  29. init(map: Map) throws
  30. }
  31. public extension ImmutableMappable {
  32. /// Implement this method to support object -> JSON transform.
  33. public func mapping(map: Map) {}
  34. /// Initializes object from a JSON String
  35. public init(JSONString: String, context: MapContext? = nil) throws {
  36. self = try Mapper(context: context).map(JSONString: JSONString)
  37. }
  38. /// Initializes object from a JSON Dictionary
  39. public init(JSON: [String: Any], context: MapContext? = nil) throws {
  40. self = try Mapper(context: context).map(JSON: JSON)
  41. }
  42. /// Initializes object from a JSONObject
  43. public init(JSONObject: Any, context: MapContext? = nil) throws {
  44. self = try Mapper(context: context).map(JSONObject: JSONObject)
  45. }
  46. }
  47. public extension Map {
  48. fileprivate func currentValue(for key: String, nested: Bool? = nil, delimiter: String = ".") -> Any? {
  49. let isNested = nested ?? key.contains(delimiter)
  50. return self[key, nested: isNested, delimiter: delimiter].currentValue
  51. }
  52. // MARK: Basic
  53. /// Returns a value or throws an error.
  54. public func value<T>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T {
  55. let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
  56. guard let value = currentValue as? T else {
  57. throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '\(T.self)'", file: file, function: function, line: line)
  58. }
  59. return value
  60. }
  61. /// Returns a transformed value or throws an error.
  62. public 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 {
  63. let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
  64. guard let value = transform.transformFromJSON(currentValue) else {
  65. throw MapError(key: key, currentValue: currentValue, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line)
  66. }
  67. return value
  68. }
  69. /// Returns a RawRepresentable type or throws an error.
  70. public func value<T: RawRepresentable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T {
  71. return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line)
  72. }
  73. /// Returns a `[RawRepresentable]` type or throws an error.
  74. public func value<T: RawRepresentable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T] {
  75. return try self.value(key, nested: nested, delimiter: delimiter, using: EnumTransform(), file: file, function: function, line: line)
  76. }
  77. // MARK: BaseMappable
  78. /// Returns a `BaseMappable` object or throws an error.
  79. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> T {
  80. let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
  81. guard let JSONObject = currentValue else {
  82. throw MapError(key: key, currentValue: currentValue, reason: "Found unexpected nil value", file: file, function: function, line: line)
  83. }
  84. return try Mapper<T>(context: context).mapOrFail(JSONObject: JSONObject)
  85. }
  86. // MARK: [BaseMappable]
  87. /// Returns a `[BaseMappable]` or throws an error.
  88. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [T] {
  89. let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
  90. guard let jsonArray = currentValue as? [Any] else {
  91. throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line)
  92. }
  93. return try jsonArray.map { JSONObject -> T in
  94. return try Mapper<T>(context: context).mapOrFail(JSONObject: JSONObject)
  95. }
  96. }
  97. /// Returns a `[BaseMappable]` using transform or throws an error.
  98. public 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] {
  99. let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
  100. guard let jsonArray = currentValue as? [Any] else {
  101. throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[Any]'", file: file, function: function, line: line)
  102. }
  103. return try jsonArray.map { json -> Transform.Object in
  104. guard let object = transform.transformFromJSON(json) else {
  105. throw MapError(key: "\(key)", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line)
  106. }
  107. return object
  108. }
  109. }
  110. // MARK: [String: BaseMappable]
  111. /// Returns a `[String: BaseMappable]` or throws an error.
  112. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [String: T] {
  113. let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
  114. guard let jsonDictionary = currentValue as? [String: Any] else {
  115. throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line)
  116. }
  117. var value: [String: T] = [:]
  118. for (key, json) in jsonDictionary {
  119. value[key] = try Mapper<T>(context: context).mapOrFail(JSONObject: json)
  120. }
  121. return value
  122. }
  123. /// Returns a `[String: BaseMappable]` using transform or throws an error.
  124. public 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] {
  125. let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
  126. guard let jsonDictionary = currentValue as? [String: Any] else {
  127. throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[String: Any]'", file: file, function: function, line: line)
  128. }
  129. var value: [String: Transform.Object] = [:]
  130. for (key, json) in jsonDictionary {
  131. guard let object = transform.transformFromJSON(json) else {
  132. throw MapError(key: key, currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line)
  133. }
  134. value[key] = object
  135. }
  136. return value
  137. }
  138. // MARK: [[BaseMappable]]
  139. /// Returns a `[[BaseMappable]]` or throws an error.
  140. public func value<T: BaseMappable>(_ key: String, nested: Bool? = nil, delimiter: String = ".", file: StaticString = #file, function: StaticString = #function, line: UInt = #line) throws -> [[T]] {
  141. let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
  142. guard let json2DArray = currentValue as? [[Any]] else {
  143. throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[[Any]]'", file: file, function: function, line: line)
  144. }
  145. return try json2DArray.map { jsonArray in
  146. try jsonArray.map { jsonObject -> T in
  147. return try Mapper<T>(context: context).mapOrFail(JSONObject: jsonObject)
  148. }
  149. }
  150. }
  151. /// Returns a `[[BaseMappable]]` using transform or throws an error.
  152. public 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]] {
  153. let currentValue = self.currentValue(for: key, nested: nested, delimiter: delimiter)
  154. guard let json2DArray = currentValue as? [[Any]] else {
  155. throw MapError(key: key, currentValue: currentValue, reason: "Cannot cast to '[[Any]]'",
  156. file: file, function: function, line: line)
  157. }
  158. return try json2DArray.map { jsonArray in
  159. try jsonArray.map { json -> Transform.Object in
  160. guard let object = transform.transformFromJSON(json) else {
  161. throw MapError(key: "\(key)", currentValue: json, reason: "Cannot transform to '\(Transform.Object.self)' using \(transform)", file: file, function: function, line: line)
  162. }
  163. return object
  164. }
  165. }
  166. }
  167. }
  168. public extension Mapper where N: ImmutableMappable {
  169. public func map(JSON: [String: Any]) throws -> N {
  170. return try self.mapOrFail(JSON: JSON)
  171. }
  172. public func map(JSONString: String) throws -> N {
  173. return try mapOrFail(JSONString: JSONString)
  174. }
  175. public func map(JSONObject: Any) throws -> N {
  176. return try mapOrFail(JSONObject: JSONObject)
  177. }
  178. // MARK: Array mapping functions
  179. public func mapArray(JSONArray: [[String: Any]]) throws -> [N] {
  180. #if swift(>=4.1)
  181. return try JSONArray.compactMap(mapOrFail)
  182. #else
  183. return try JSONArray.flatMap(mapOrFail)
  184. #endif
  185. }
  186. public func mapArray(JSONString: String) throws -> [N] {
  187. guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else {
  188. throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'")
  189. }
  190. return try mapArray(JSONObject: JSONObject)
  191. }
  192. public func mapArray(JSONObject: Any) throws -> [N] {
  193. guard let JSONArray = JSONObject as? [[String: Any]] else {
  194. throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[String: Any]]'")
  195. }
  196. return try mapArray(JSONArray: JSONArray)
  197. }
  198. // MARK: Dictionary mapping functions
  199. public func mapDictionary(JSONString: String) throws -> [String: N] {
  200. guard let JSONObject = Mapper.parseJSONString(JSONString: JSONString) else {
  201. throw MapError(key: nil, currentValue: JSONString, reason: "Cannot convert string into Any'")
  202. }
  203. return try mapDictionary(JSONObject: JSONObject)
  204. }
  205. public func mapDictionary(JSONObject: Any?) throws -> [String: N] {
  206. guard let JSON = JSONObject as? [String: [String: Any]] else {
  207. throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''")
  208. }
  209. return try mapDictionary(JSON: JSON)
  210. }
  211. public func mapDictionary(JSON: [String: [String: Any]]) throws -> [String: N] {
  212. return try JSON.filterMap(mapOrFail)
  213. }
  214. // MARK: Dictinoary of arrays mapping functions
  215. public func mapDictionaryOfArrays(JSONObject: Any?) throws -> [String: [N]] {
  216. guard let JSON = JSONObject as? [String: [[String: Any]]] else {
  217. throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: [String: Any]]''")
  218. }
  219. return try mapDictionaryOfArrays(JSON: JSON)
  220. }
  221. public func mapDictionaryOfArrays(JSON: [String: [[String: Any]]]) throws -> [String: [N]] {
  222. return try JSON.filterMap { array -> [N] in
  223. try mapArray(JSONArray: array)
  224. }
  225. }
  226. // MARK: 2 dimentional array mapping functions
  227. public func mapArrayOfArrays(JSONObject: Any?) throws -> [[N]] {
  228. guard let JSONArray = JSONObject as? [[[String: Any]]] else {
  229. throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[[[String: Any]]]''")
  230. }
  231. return try JSONArray.map(mapArray)
  232. }
  233. }
  234. internal extension Mapper {
  235. internal func mapOrFail(JSON: [String: Any]) throws -> N {
  236. let map = Map(mappingType: .fromJSON, JSON: JSON, context: context, shouldIncludeNilValues: shouldIncludeNilValues)
  237. // Check if object is ImmutableMappable, if so use ImmutableMappable protocol for mapping
  238. if let klass = N.self as? ImmutableMappable.Type,
  239. var object = try klass.init(map: map) as? N {
  240. object.mapping(map: map)
  241. return object
  242. }
  243. // If not, map the object the standard way
  244. guard let value = self.map(JSON: JSON) else {
  245. throw MapError(key: nil, currentValue: JSON, reason: "Cannot map to '\(N.self)'")
  246. }
  247. return value
  248. }
  249. internal func mapOrFail(JSONString: String) throws -> N {
  250. guard let JSON = Mapper.parseJSONStringIntoDictionary(JSONString: JSONString) else {
  251. throw MapError(key: nil, currentValue: JSONString, reason: "Cannot parse into '[String: Any]'")
  252. }
  253. return try mapOrFail(JSON: JSON)
  254. }
  255. internal func mapOrFail(JSONObject: Any) throws -> N {
  256. guard let JSON = JSONObject as? [String: Any] else {
  257. throw MapError(key: nil, currentValue: JSONObject, reason: "Cannot cast to '[String: Any]'")
  258. }
  259. return try mapOrFail(JSON: JSON)
  260. }
  261. }