URLEncodedFormEncoder.swift 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. //
  2. // URLEncodedFormEncoder.swift
  3. //
  4. // Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// An object that encodes instances into URL-encoded query strings.
  26. ///
  27. /// `ArrayEncoding` can be used to configure how `Array` values are encoded. By default, the `.brackets` encoding is
  28. /// used, encoding array values with brackets for each value. e.g `array[]=1&array[]=2`.
  29. ///
  30. /// `BoolEncoding` can be used to configure how `Bool` values are encoded. By default, the `.numeric` encoding is used,
  31. /// encoding `true` as `1` and `false` as `0`.
  32. ///
  33. /// `DataEncoding` can be used to configure how `Data` values are encoded. By default, the `.deferredToData` encoding is
  34. /// used, which encodes `Data` values using their default `Encodable` implementation.
  35. ///
  36. /// `DateEncoding` can be used to configure how `Date` values are encoded. By default, the `.deferredToDate`
  37. /// encoding is used, which encodes `Date`s using their default `Encodable` implementation.
  38. ///
  39. /// `KeyEncoding` can be used to configure how keys are encoded. By default, the `.useDefaultKeys` encoding is used,
  40. /// which encodes the keys directly from the `Encodable` implementation.
  41. ///
  42. /// `KeyPathEncoding` can be used to configure how paths within nested objects are encoded. By default, the `.brackets`
  43. /// encoding is used, which encodes each sub-key in brackets. e.g. `parent[child][grandchild]=value`.
  44. ///
  45. /// `NilEncoding` can be used to configure how `nil` `Optional` values are encoded. By default, the `.dropKey` encoding
  46. /// is used, which drops `nil` key / value pairs from the output entirely.
  47. ///
  48. /// `SpaceEncoding` can be used to configure how spaces are encoded. By default, the `.percentEscaped` encoding is used,
  49. /// replacing spaces with `%20`.
  50. ///
  51. /// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project.
  52. public final class URLEncodedFormEncoder {
  53. /// Encoding to use for `Array` values.
  54. public enum ArrayEncoding {
  55. /// An empty set of square brackets ("[]") are appended to the key for every value. This is the default encoding.
  56. case brackets
  57. /// No brackets are appended to the key and the key is encoded as is.
  58. case noBrackets
  59. /// Brackets containing the item index are appended. This matches the jQuery and Node.js behavior.
  60. case indexInBrackets
  61. /// Encodes the key according to the encoding.
  62. ///
  63. /// - Parameters:
  64. /// - key: The `key` to encode.
  65. /// - index: When this enum instance is `.indexInBrackets`, the `index` to encode.
  66. ///
  67. /// - Returns: The encoded key.
  68. func encode(_ key: String, atIndex index: Int) -> String {
  69. switch self {
  70. case .brackets: return "\(key)[]"
  71. case .noBrackets: return key
  72. case .indexInBrackets: return "\(key)[\(index)]"
  73. }
  74. }
  75. }
  76. /// Encoding to use for `Bool` values.
  77. public enum BoolEncoding {
  78. /// Encodes `true` as `1`, `false` as `0`.
  79. case numeric
  80. /// Encodes `true` as "true", `false` as "false". This is the default encoding.
  81. case literal
  82. /// Encodes the given `Bool` as a `String`.
  83. ///
  84. /// - Parameter value: The `Bool` to encode.
  85. ///
  86. /// - Returns: The encoded `String`.
  87. func encode(_ value: Bool) -> String {
  88. switch self {
  89. case .numeric: return value ? "1" : "0"
  90. case .literal: return value ? "true" : "false"
  91. }
  92. }
  93. }
  94. /// Encoding to use for `Data` values.
  95. public enum DataEncoding {
  96. /// Defers encoding to the `Data` type.
  97. case deferredToData
  98. /// Encodes `Data` as a Base64-encoded string. This is the default encoding.
  99. case base64
  100. /// Encode the `Data` as a custom value encoded by the given closure.
  101. case custom((Data) throws -> String)
  102. /// Encodes `Data` according to the encoding.
  103. ///
  104. /// - Parameter data: The `Data` to encode.
  105. ///
  106. /// - Returns: The encoded `String`, or `nil` if the `Data` should be encoded according to its
  107. /// `Encodable` implementation.
  108. func encode(_ data: Data) throws -> String? {
  109. switch self {
  110. case .deferredToData: return nil
  111. case .base64: return data.base64EncodedString()
  112. case let .custom(encoding): return try encoding(data)
  113. }
  114. }
  115. }
  116. /// Encoding to use for `Date` values.
  117. public enum DateEncoding {
  118. /// ISO8601 and RFC3339 formatter.
  119. private static let iso8601Formatter: ISO8601DateFormatter = {
  120. let formatter = ISO8601DateFormatter()
  121. formatter.formatOptions = .withInternetDateTime
  122. return formatter
  123. }()
  124. /// Defers encoding to the `Date` type. This is the default encoding.
  125. case deferredToDate
  126. /// Encodes `Date`s as seconds since midnight UTC on January 1, 1970.
  127. case secondsSince1970
  128. /// Encodes `Date`s as milliseconds since midnight UTC on January 1, 1970.
  129. case millisecondsSince1970
  130. /// Encodes `Date`s according to the ISO8601 and RFC3339 standards.
  131. case iso8601
  132. /// Encodes `Date`s using the given `DateFormatter`.
  133. case formatted(DateFormatter)
  134. /// Encodes `Date`s using the given closure.
  135. case custom((Date) throws -> String)
  136. /// Encodes the date according to the encoding.
  137. ///
  138. /// - Parameter date: The `Date` to encode.
  139. ///
  140. /// - Returns: The encoded `String`, or `nil` if the `Date` should be encoded according to its
  141. /// `Encodable` implementation.
  142. func encode(_ date: Date) throws -> String? {
  143. switch self {
  144. case .deferredToDate:
  145. return nil
  146. case .secondsSince1970:
  147. return String(date.timeIntervalSince1970)
  148. case .millisecondsSince1970:
  149. return String(date.timeIntervalSince1970 * 1000.0)
  150. case .iso8601:
  151. return DateEncoding.iso8601Formatter.string(from: date)
  152. case let .formatted(formatter):
  153. return formatter.string(from: date)
  154. case let .custom(closure):
  155. return try closure(date)
  156. }
  157. }
  158. }
  159. /// Encoding to use for keys.
  160. ///
  161. /// This type is derived from [`JSONEncoder`'s `KeyEncodingStrategy`](https://github.com/apple/swift/blob/6aa313b8dd5f05135f7f878eccc1db6f9fbe34ff/stdlib/public/Darwin/Foundation/JSONEncoder.swift#L128)
  162. /// and [`XMLEncoder`s `KeyEncodingStrategy`](https://github.com/MaxDesiatov/XMLCoder/blob/master/Sources/XMLCoder/Encoder/XMLEncoder.swift#L102).
  163. public enum KeyEncoding {
  164. /// Use the keys specified by each type. This is the default encoding.
  165. case useDefaultKeys
  166. /// Convert from "camelCaseKeys" to "snake_case_keys" before writing a key.
  167. ///
  168. /// Capital characters are determined by testing membership in
  169. /// `CharacterSet.uppercaseLetters` and `CharacterSet.lowercaseLetters`
  170. /// (Unicode General Categories Lu and Lt).
  171. /// The conversion to lower case uses `Locale.system`, also known as
  172. /// the ICU "root" locale. This means the result is consistent
  173. /// regardless of the current user's locale and language preferences.
  174. ///
  175. /// Converting from camel case to snake case:
  176. /// 1. Splits words at the boundary of lower-case to upper-case
  177. /// 2. Inserts `_` between words
  178. /// 3. Lowercases the entire string
  179. /// 4. Preserves starting and ending `_`.
  180. ///
  181. /// For example, `oneTwoThree` becomes `one_two_three`. `_oneTwoThree_` becomes `_one_two_three_`.
  182. ///
  183. /// - Note: Using a key encoding strategy has a nominal performance cost, as each string key has to be converted.
  184. case convertToSnakeCase
  185. /// Same as convertToSnakeCase, but using `-` instead of `_`.
  186. /// For example `oneTwoThree` becomes `one-two-three`.
  187. case convertToKebabCase
  188. /// Capitalize the first letter only.
  189. /// For example `oneTwoThree` becomes `OneTwoThree`.
  190. case capitalized
  191. /// Uppercase all letters.
  192. /// For example `oneTwoThree` becomes `ONETWOTHREE`.
  193. case uppercased
  194. /// Lowercase all letters.
  195. /// For example `oneTwoThree` becomes `onetwothree`.
  196. case lowercased
  197. /// A custom encoding using the provided closure.
  198. case custom((String) -> String)
  199. func encode(_ key: String) -> String {
  200. switch self {
  201. case .useDefaultKeys: return key
  202. case .convertToSnakeCase: return convertToSnakeCase(key)
  203. case .convertToKebabCase: return convertToKebabCase(key)
  204. case .capitalized: return String(key.prefix(1).uppercased() + key.dropFirst())
  205. case .uppercased: return key.uppercased()
  206. case .lowercased: return key.lowercased()
  207. case let .custom(encoding): return encoding(key)
  208. }
  209. }
  210. private func convertToSnakeCase(_ key: String) -> String {
  211. convert(key, usingSeparator: "_")
  212. }
  213. private func convertToKebabCase(_ key: String) -> String {
  214. convert(key, usingSeparator: "-")
  215. }
  216. private func convert(_ key: String, usingSeparator separator: String) -> String {
  217. guard !key.isEmpty else { return key }
  218. var words: [Range<String.Index>] = []
  219. // The general idea of this algorithm is to split words on
  220. // transition from lower to upper case, then on transition of >1
  221. // upper case characters to lowercase
  222. //
  223. // myProperty -> my_property
  224. // myURLProperty -> my_url_property
  225. //
  226. // It is assumed, per Swift naming conventions, that the first character of the key is lowercase.
  227. var wordStart = key.startIndex
  228. var searchRange = key.index(after: wordStart)..<key.endIndex
  229. // Find next uppercase character
  230. while let upperCaseRange = key.rangeOfCharacter(from: .uppercaseLetters, options: [], range: searchRange) {
  231. let untilUpperCase = wordStart..<upperCaseRange.lowerBound
  232. words.append(untilUpperCase)
  233. // Find next lowercase character
  234. searchRange = upperCaseRange.lowerBound..<searchRange.upperBound
  235. guard let lowerCaseRange = key.rangeOfCharacter(from: .lowercaseLetters, options: [], range: searchRange) else {
  236. // There are no more lower case letters. Just end here.
  237. wordStart = searchRange.lowerBound
  238. break
  239. }
  240. // Is the next lowercase letter more than 1 after the uppercase?
  241. // If so, we encountered a group of uppercase letters that we
  242. // should treat as its own word
  243. let nextCharacterAfterCapital = key.index(after: upperCaseRange.lowerBound)
  244. if lowerCaseRange.lowerBound == nextCharacterAfterCapital {
  245. // The next character after capital is a lower case character and therefore not a word boundary.
  246. // Continue searching for the next upper case for the boundary.
  247. wordStart = upperCaseRange.lowerBound
  248. } else {
  249. // There was a range of >1 capital letters. Turn those into a word, stopping at the capital before
  250. // the lower case character.
  251. let beforeLowerIndex = key.index(before: lowerCaseRange.lowerBound)
  252. words.append(upperCaseRange.lowerBound..<beforeLowerIndex)
  253. // Next word starts at the capital before the lowercase we just found
  254. wordStart = beforeLowerIndex
  255. }
  256. searchRange = lowerCaseRange.upperBound..<searchRange.upperBound
  257. }
  258. words.append(wordStart..<searchRange.upperBound)
  259. let result = words.map { range in
  260. key[range].lowercased()
  261. }.joined(separator: separator)
  262. return result
  263. }
  264. }
  265. /// Encoding to use for nested object and `Encodable` value key paths.
  266. ///
  267. /// ```
  268. /// ["parent" : ["child" : ["grandchild": "value"]]]
  269. /// ```
  270. ///
  271. /// This encoding affects how the `parent`, `child`, `grandchild` path is encoded. Brackets are used by default.
  272. /// e.g. `parent[child][grandchild]=value`.
  273. public struct KeyPathEncoding {
  274. /// Encodes key paths by wrapping each component in brackets. e.g. `parent[child][grandchild]`.
  275. public static let brackets = KeyPathEncoding { "[\($0)]" }
  276. /// Encodes key paths by separating each component with dots. e.g. `parent.child.grandchild`.
  277. public static let dots = KeyPathEncoding { ".\($0)" }
  278. private let encoding: (_ subkey: String) -> String
  279. /// Creates an instance with the encoding closure called for each sub-key in a key path.
  280. ///
  281. /// - Parameter encoding: Closure used to perform the encoding.
  282. public init(encoding: @escaping (_ subkey: String) -> String) {
  283. self.encoding = encoding
  284. }
  285. func encodeKeyPath(_ keyPath: String) -> String {
  286. encoding(keyPath)
  287. }
  288. }
  289. /// Encoding to use for `nil` values.
  290. public struct NilEncoding {
  291. /// Encodes `nil` by dropping the entire key / value pair.
  292. public static let dropKey = NilEncoding { nil }
  293. /// Encodes `nil` by dropping only the value. e.g. `value1=one&nilValue=&value2=two`.
  294. public static let dropValue = NilEncoding { "" }
  295. /// Encodes `nil` as `null`.
  296. public static let null = NilEncoding { "null" }
  297. private let encoding: () -> String?
  298. /// Creates an instance with the encoding closure called for `nil` values.
  299. ///
  300. /// - Parameter encoding: Closure used to perform the encoding.
  301. public init(encoding: @escaping () -> String?) {
  302. self.encoding = encoding
  303. }
  304. func encodeNil() -> String? {
  305. encoding()
  306. }
  307. }
  308. /// Encoding to use for spaces.
  309. public enum SpaceEncoding {
  310. /// Encodes spaces using percent escaping (`%20`).
  311. case percentEscaped
  312. /// Encodes spaces as `+`.
  313. case plusReplaced
  314. /// Encodes the string according to the encoding.
  315. ///
  316. /// - Parameter string: The `String` to encode.
  317. ///
  318. /// - Returns: The encoded `String`.
  319. func encode(_ string: String) -> String {
  320. switch self {
  321. case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20")
  322. case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+")
  323. }
  324. }
  325. }
  326. /// `URLEncodedFormEncoder` error.
  327. public enum Error: Swift.Error {
  328. /// An invalid root object was created by the encoder. Only keyed values are valid.
  329. case invalidRootObject(String)
  330. var localizedDescription: String {
  331. switch self {
  332. case let .invalidRootObject(object):
  333. return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead."
  334. }
  335. }
  336. }
  337. /// Whether or not to sort the encoded key value pairs.
  338. ///
  339. /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`,
  340. /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to
  341. /// ` Dictionary`'s random storage order, but `Encodable` types will maintain their encoded order.
  342. public let alphabetizeKeyValuePairs: Bool
  343. /// The `ArrayEncoding` to use.
  344. public let arrayEncoding: ArrayEncoding
  345. /// The `BoolEncoding` to use.
  346. public let boolEncoding: BoolEncoding
  347. /// THe `DataEncoding` to use.
  348. public let dataEncoding: DataEncoding
  349. /// The `DateEncoding` to use.
  350. public let dateEncoding: DateEncoding
  351. /// The `KeyEncoding` to use.
  352. public let keyEncoding: KeyEncoding
  353. /// The `KeyPathEncoding` to use.
  354. public let keyPathEncoding: KeyPathEncoding
  355. /// The `NilEncoding` to use.
  356. public let nilEncoding: NilEncoding
  357. /// The `SpaceEncoding` to use.
  358. public let spaceEncoding: SpaceEncoding
  359. /// The `CharacterSet` of allowed (non-escaped) characters.
  360. public var allowedCharacters: CharacterSet
  361. /// Creates an instance from the supplied parameters.
  362. ///
  363. /// - Parameters:
  364. /// - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default.
  365. /// - arrayEncoding: The `ArrayEncoding` to use. `.brackets` by default.
  366. /// - boolEncoding: The `BoolEncoding` to use. `.numeric` by default.
  367. /// - dataEncoding: The `DataEncoding` to use. `.base64` by default.
  368. /// - dateEncoding: The `DateEncoding` to use. `.deferredToDate` by default.
  369. /// - keyEncoding: The `KeyEncoding` to use. `.useDefaultKeys` by default.
  370. /// - nilEncoding: The `NilEncoding` to use. `.drop` by default.
  371. /// - spaceEncoding: The `SpaceEncoding` to use. `.percentEscaped` by default.
  372. /// - allowedCharacters: The `CharacterSet` of allowed (non-escaped) characters. `.afURLQueryAllowed` by
  373. /// default.
  374. public init(alphabetizeKeyValuePairs: Bool = true,
  375. arrayEncoding: ArrayEncoding = .brackets,
  376. boolEncoding: BoolEncoding = .numeric,
  377. dataEncoding: DataEncoding = .base64,
  378. dateEncoding: DateEncoding = .deferredToDate,
  379. keyEncoding: KeyEncoding = .useDefaultKeys,
  380. keyPathEncoding: KeyPathEncoding = .brackets,
  381. nilEncoding: NilEncoding = .dropKey,
  382. spaceEncoding: SpaceEncoding = .percentEscaped,
  383. allowedCharacters: CharacterSet = .afURLQueryAllowed) {
  384. self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs
  385. self.arrayEncoding = arrayEncoding
  386. self.boolEncoding = boolEncoding
  387. self.dataEncoding = dataEncoding
  388. self.dateEncoding = dateEncoding
  389. self.keyEncoding = keyEncoding
  390. self.keyPathEncoding = keyPathEncoding
  391. self.nilEncoding = nilEncoding
  392. self.spaceEncoding = spaceEncoding
  393. self.allowedCharacters = allowedCharacters
  394. }
  395. func encode(_ value: Encodable) throws -> URLEncodedFormComponent {
  396. let context = URLEncodedFormContext(.object([]))
  397. let encoder = _URLEncodedFormEncoder(context: context,
  398. boolEncoding: boolEncoding,
  399. dataEncoding: dataEncoding,
  400. dateEncoding: dateEncoding,
  401. nilEncoding: nilEncoding)
  402. try value.encode(to: encoder)
  403. return context.component
  404. }
  405. /// Encodes the `value` as a URL form encoded `String`.
  406. ///
  407. /// - Parameter value: The `Encodable` value.`
  408. ///
  409. /// - Returns: The encoded `String`.
  410. /// - Throws: An `Error` or `EncodingError` instance if encoding fails.
  411. public func encode(_ value: Encodable) throws -> String {
  412. let component: URLEncodedFormComponent = try encode(value)
  413. guard case let .object(object) = component else {
  414. throw Error.invalidRootObject("\(component)")
  415. }
  416. let serializer = URLEncodedFormSerializer(alphabetizeKeyValuePairs: alphabetizeKeyValuePairs,
  417. arrayEncoding: arrayEncoding,
  418. keyEncoding: keyEncoding,
  419. keyPathEncoding: keyPathEncoding,
  420. spaceEncoding: spaceEncoding,
  421. allowedCharacters: allowedCharacters)
  422. let query = serializer.serialize(object)
  423. return query
  424. }
  425. /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the
  426. /// `.utf8` data.
  427. ///
  428. /// - Parameter value: The `Encodable` value.
  429. ///
  430. /// - Returns: The encoded `Data`.
  431. ///
  432. /// - Throws: An `Error` or `EncodingError` instance if encoding fails.
  433. public func encode(_ value: Encodable) throws -> Data {
  434. let string: String = try encode(value)
  435. return Data(string.utf8)
  436. }
  437. }
  438. final class _URLEncodedFormEncoder {
  439. var codingPath: [CodingKey]
  440. // Returns an empty dictionary, as this encoder doesn't support userInfo.
  441. var userInfo: [CodingUserInfoKey: Any] { [:] }
  442. let context: URLEncodedFormContext
  443. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  444. private let dataEncoding: URLEncodedFormEncoder.DataEncoding
  445. private let dateEncoding: URLEncodedFormEncoder.DateEncoding
  446. private let nilEncoding: URLEncodedFormEncoder.NilEncoding
  447. init(context: URLEncodedFormContext,
  448. codingPath: [CodingKey] = [],
  449. boolEncoding: URLEncodedFormEncoder.BoolEncoding,
  450. dataEncoding: URLEncodedFormEncoder.DataEncoding,
  451. dateEncoding: URLEncodedFormEncoder.DateEncoding,
  452. nilEncoding: URLEncodedFormEncoder.NilEncoding) {
  453. self.context = context
  454. self.codingPath = codingPath
  455. self.boolEncoding = boolEncoding
  456. self.dataEncoding = dataEncoding
  457. self.dateEncoding = dateEncoding
  458. self.nilEncoding = nilEncoding
  459. }
  460. }
  461. extension _URLEncodedFormEncoder: Encoder {
  462. func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
  463. let container = _URLEncodedFormEncoder.KeyedContainer<Key>(context: context,
  464. codingPath: codingPath,
  465. boolEncoding: boolEncoding,
  466. dataEncoding: dataEncoding,
  467. dateEncoding: dateEncoding,
  468. nilEncoding: nilEncoding)
  469. return KeyedEncodingContainer(container)
  470. }
  471. func unkeyedContainer() -> UnkeyedEncodingContainer {
  472. _URLEncodedFormEncoder.UnkeyedContainer(context: context,
  473. codingPath: codingPath,
  474. boolEncoding: boolEncoding,
  475. dataEncoding: dataEncoding,
  476. dateEncoding: dateEncoding,
  477. nilEncoding: nilEncoding)
  478. }
  479. func singleValueContainer() -> SingleValueEncodingContainer {
  480. _URLEncodedFormEncoder.SingleValueContainer(context: context,
  481. codingPath: codingPath,
  482. boolEncoding: boolEncoding,
  483. dataEncoding: dataEncoding,
  484. dateEncoding: dateEncoding,
  485. nilEncoding: nilEncoding)
  486. }
  487. }
  488. final class URLEncodedFormContext {
  489. var component: URLEncodedFormComponent
  490. init(_ component: URLEncodedFormComponent) {
  491. self.component = component
  492. }
  493. }
  494. enum URLEncodedFormComponent {
  495. typealias Object = [(key: String, value: URLEncodedFormComponent)]
  496. case string(String)
  497. case array([URLEncodedFormComponent])
  498. case object(Object)
  499. /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible.
  500. var array: [URLEncodedFormComponent]? {
  501. switch self {
  502. case let .array(array): return array
  503. default: return nil
  504. }
  505. }
  506. /// Converts self to an `Object` or returns `nil` if not convertible.
  507. var object: Object? {
  508. switch self {
  509. case let .object(object): return object
  510. default: return nil
  511. }
  512. }
  513. /// Sets self to the supplied value at a given path.
  514. ///
  515. /// data.set(to: "hello", at: ["path", "to", "value"])
  516. ///
  517. /// - parameters:
  518. /// - value: Value of `Self` to set at the supplied path.
  519. /// - path: `CodingKey` path to update with the supplied value.
  520. public mutating func set(to value: URLEncodedFormComponent, at path: [CodingKey]) {
  521. set(&self, to: value, at: path)
  522. }
  523. /// Recursive backing method to `set(to:at:)`.
  524. private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [CodingKey]) {
  525. guard !path.isEmpty else {
  526. context = value
  527. return
  528. }
  529. let end = path[0]
  530. var child: URLEncodedFormComponent
  531. switch path.count {
  532. case 1:
  533. child = value
  534. case 2...:
  535. if let index = end.intValue {
  536. let array = context.array ?? []
  537. if array.count > index {
  538. child = array[index]
  539. } else {
  540. child = .array([])
  541. }
  542. set(&child, to: value, at: Array(path[1...]))
  543. } else {
  544. child = context.object?.first { $0.key == end.stringValue }?.value ?? .object(.init())
  545. set(&child, to: value, at: Array(path[1...]))
  546. }
  547. default: fatalError("Unreachable")
  548. }
  549. if let index = end.intValue {
  550. if var array = context.array {
  551. if array.count > index {
  552. array[index] = child
  553. } else {
  554. array.append(child)
  555. }
  556. context = .array(array)
  557. } else {
  558. context = .array([child])
  559. }
  560. } else {
  561. if var object = context.object {
  562. if let index = object.firstIndex(where: { $0.key == end.stringValue }) {
  563. object[index] = (key: end.stringValue, value: child)
  564. } else {
  565. object.append((key: end.stringValue, value: child))
  566. }
  567. context = .object(object)
  568. } else {
  569. context = .object([(key: end.stringValue, value: child)])
  570. }
  571. }
  572. }
  573. }
  574. struct AnyCodingKey: CodingKey, Hashable {
  575. let stringValue: String
  576. let intValue: Int?
  577. init?(stringValue: String) {
  578. self.stringValue = stringValue
  579. intValue = nil
  580. }
  581. init?(intValue: Int) {
  582. stringValue = "\(intValue)"
  583. self.intValue = intValue
  584. }
  585. init<Key>(_ base: Key) where Key: CodingKey {
  586. if let intValue = base.intValue {
  587. self.init(intValue: intValue)!
  588. } else {
  589. self.init(stringValue: base.stringValue)!
  590. }
  591. }
  592. }
  593. extension _URLEncodedFormEncoder {
  594. final class KeyedContainer<Key> where Key: CodingKey {
  595. var codingPath: [CodingKey]
  596. private let context: URLEncodedFormContext
  597. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  598. private let dataEncoding: URLEncodedFormEncoder.DataEncoding
  599. private let dateEncoding: URLEncodedFormEncoder.DateEncoding
  600. private let nilEncoding: URLEncodedFormEncoder.NilEncoding
  601. init(context: URLEncodedFormContext,
  602. codingPath: [CodingKey],
  603. boolEncoding: URLEncodedFormEncoder.BoolEncoding,
  604. dataEncoding: URLEncodedFormEncoder.DataEncoding,
  605. dateEncoding: URLEncodedFormEncoder.DateEncoding,
  606. nilEncoding: URLEncodedFormEncoder.NilEncoding) {
  607. self.context = context
  608. self.codingPath = codingPath
  609. self.boolEncoding = boolEncoding
  610. self.dataEncoding = dataEncoding
  611. self.dateEncoding = dateEncoding
  612. self.nilEncoding = nilEncoding
  613. }
  614. private func nestedCodingPath(for key: CodingKey) -> [CodingKey] {
  615. codingPath + [key]
  616. }
  617. }
  618. }
  619. extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol {
  620. func encodeNil(forKey key: Key) throws {
  621. guard let nilValue = nilEncoding.encodeNil() else { return }
  622. try encode(nilValue, forKey: key)
  623. }
  624. func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable {
  625. var container = nestedSingleValueEncoder(for: key)
  626. try container.encode(value)
  627. }
  628. func nestedSingleValueEncoder(for key: Key) -> SingleValueEncodingContainer {
  629. let container = _URLEncodedFormEncoder.SingleValueContainer(context: context,
  630. codingPath: nestedCodingPath(for: key),
  631. boolEncoding: boolEncoding,
  632. dataEncoding: dataEncoding,
  633. dateEncoding: dateEncoding,
  634. nilEncoding: nilEncoding)
  635. return container
  636. }
  637. func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
  638. let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context,
  639. codingPath: nestedCodingPath(for: key),
  640. boolEncoding: boolEncoding,
  641. dataEncoding: dataEncoding,
  642. dateEncoding: dateEncoding,
  643. nilEncoding: nilEncoding)
  644. return container
  645. }
  646. func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
  647. let container = _URLEncodedFormEncoder.KeyedContainer<NestedKey>(context: context,
  648. codingPath: nestedCodingPath(for: key),
  649. boolEncoding: boolEncoding,
  650. dataEncoding: dataEncoding,
  651. dateEncoding: dateEncoding,
  652. nilEncoding: nilEncoding)
  653. return KeyedEncodingContainer(container)
  654. }
  655. func superEncoder() -> Encoder {
  656. _URLEncodedFormEncoder(context: context,
  657. codingPath: codingPath,
  658. boolEncoding: boolEncoding,
  659. dataEncoding: dataEncoding,
  660. dateEncoding: dateEncoding,
  661. nilEncoding: nilEncoding)
  662. }
  663. func superEncoder(forKey key: Key) -> Encoder {
  664. _URLEncodedFormEncoder(context: context,
  665. codingPath: nestedCodingPath(for: key),
  666. boolEncoding: boolEncoding,
  667. dataEncoding: dataEncoding,
  668. dateEncoding: dateEncoding,
  669. nilEncoding: nilEncoding)
  670. }
  671. }
  672. extension _URLEncodedFormEncoder {
  673. final class SingleValueContainer {
  674. var codingPath: [CodingKey]
  675. private var canEncodeNewValue = true
  676. private let context: URLEncodedFormContext
  677. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  678. private let dataEncoding: URLEncodedFormEncoder.DataEncoding
  679. private let dateEncoding: URLEncodedFormEncoder.DateEncoding
  680. private let nilEncoding: URLEncodedFormEncoder.NilEncoding
  681. init(context: URLEncodedFormContext,
  682. codingPath: [CodingKey],
  683. boolEncoding: URLEncodedFormEncoder.BoolEncoding,
  684. dataEncoding: URLEncodedFormEncoder.DataEncoding,
  685. dateEncoding: URLEncodedFormEncoder.DateEncoding,
  686. nilEncoding: URLEncodedFormEncoder.NilEncoding) {
  687. self.context = context
  688. self.codingPath = codingPath
  689. self.boolEncoding = boolEncoding
  690. self.dataEncoding = dataEncoding
  691. self.dateEncoding = dateEncoding
  692. self.nilEncoding = nilEncoding
  693. }
  694. private func checkCanEncode(value: Any?) throws {
  695. guard canEncodeNewValue else {
  696. let context = EncodingError.Context(codingPath: codingPath,
  697. debugDescription: "Attempt to encode value through single value container when previously value already encoded.")
  698. throw EncodingError.invalidValue(value as Any, context)
  699. }
  700. }
  701. }
  702. }
  703. extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer {
  704. func encodeNil() throws {
  705. guard let nilValue = nilEncoding.encodeNil() else { return }
  706. try encode(nilValue)
  707. }
  708. func encode(_ value: Bool) throws {
  709. try encode(value, as: String(boolEncoding.encode(value)))
  710. }
  711. func encode(_ value: String) throws {
  712. try encode(value, as: value)
  713. }
  714. func encode(_ value: Double) throws {
  715. try encode(value, as: String(value))
  716. }
  717. func encode(_ value: Float) throws {
  718. try encode(value, as: String(value))
  719. }
  720. func encode(_ value: Int) throws {
  721. try encode(value, as: String(value))
  722. }
  723. func encode(_ value: Int8) throws {
  724. try encode(value, as: String(value))
  725. }
  726. func encode(_ value: Int16) throws {
  727. try encode(value, as: String(value))
  728. }
  729. func encode(_ value: Int32) throws {
  730. try encode(value, as: String(value))
  731. }
  732. func encode(_ value: Int64) throws {
  733. try encode(value, as: String(value))
  734. }
  735. func encode(_ value: UInt) throws {
  736. try encode(value, as: String(value))
  737. }
  738. func encode(_ value: UInt8) throws {
  739. try encode(value, as: String(value))
  740. }
  741. func encode(_ value: UInt16) throws {
  742. try encode(value, as: String(value))
  743. }
  744. func encode(_ value: UInt32) throws {
  745. try encode(value, as: String(value))
  746. }
  747. func encode(_ value: UInt64) throws {
  748. try encode(value, as: String(value))
  749. }
  750. private func encode<T>(_ value: T, as string: String) throws where T: Encodable {
  751. try checkCanEncode(value: value)
  752. defer { canEncodeNewValue = false }
  753. context.component.set(to: .string(string), at: codingPath)
  754. }
  755. func encode<T>(_ value: T) throws where T: Encodable {
  756. switch value {
  757. case let date as Date:
  758. guard let string = try dateEncoding.encode(date) else {
  759. try attemptToEncode(value)
  760. return
  761. }
  762. try encode(value, as: string)
  763. case let data as Data:
  764. guard let string = try dataEncoding.encode(data) else {
  765. try attemptToEncode(value)
  766. return
  767. }
  768. try encode(value, as: string)
  769. case let decimal as Decimal:
  770. // Decimal's `Encodable` implementation returns an object, not a single value, so override it.
  771. try encode(value, as: String(describing: decimal))
  772. default:
  773. try attemptToEncode(value)
  774. }
  775. }
  776. private func attemptToEncode<T>(_ value: T) throws where T: Encodable {
  777. try checkCanEncode(value: value)
  778. defer { canEncodeNewValue = false }
  779. let encoder = _URLEncodedFormEncoder(context: context,
  780. codingPath: codingPath,
  781. boolEncoding: boolEncoding,
  782. dataEncoding: dataEncoding,
  783. dateEncoding: dateEncoding,
  784. nilEncoding: nilEncoding)
  785. try value.encode(to: encoder)
  786. }
  787. }
  788. extension _URLEncodedFormEncoder {
  789. final class UnkeyedContainer {
  790. var codingPath: [CodingKey]
  791. var count = 0
  792. var nestedCodingPath: [CodingKey] {
  793. codingPath + [AnyCodingKey(intValue: count)!]
  794. }
  795. private let context: URLEncodedFormContext
  796. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  797. private let dataEncoding: URLEncodedFormEncoder.DataEncoding
  798. private let dateEncoding: URLEncodedFormEncoder.DateEncoding
  799. private let nilEncoding: URLEncodedFormEncoder.NilEncoding
  800. init(context: URLEncodedFormContext,
  801. codingPath: [CodingKey],
  802. boolEncoding: URLEncodedFormEncoder.BoolEncoding,
  803. dataEncoding: URLEncodedFormEncoder.DataEncoding,
  804. dateEncoding: URLEncodedFormEncoder.DateEncoding,
  805. nilEncoding: URLEncodedFormEncoder.NilEncoding) {
  806. self.context = context
  807. self.codingPath = codingPath
  808. self.boolEncoding = boolEncoding
  809. self.dataEncoding = dataEncoding
  810. self.dateEncoding = dateEncoding
  811. self.nilEncoding = nilEncoding
  812. }
  813. }
  814. }
  815. extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer {
  816. func encodeNil() throws {
  817. guard let nilValue = nilEncoding.encodeNil() else { return }
  818. try encode(nilValue)
  819. }
  820. func encode<T>(_ value: T) throws where T: Encodable {
  821. var container = nestedSingleValueContainer()
  822. try container.encode(value)
  823. }
  824. func nestedSingleValueContainer() -> SingleValueEncodingContainer {
  825. defer { count += 1 }
  826. return _URLEncodedFormEncoder.SingleValueContainer(context: context,
  827. codingPath: nestedCodingPath,
  828. boolEncoding: boolEncoding,
  829. dataEncoding: dataEncoding,
  830. dateEncoding: dateEncoding,
  831. nilEncoding: nilEncoding)
  832. }
  833. func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
  834. defer { count += 1 }
  835. let container = _URLEncodedFormEncoder.KeyedContainer<NestedKey>(context: context,
  836. codingPath: nestedCodingPath,
  837. boolEncoding: boolEncoding,
  838. dataEncoding: dataEncoding,
  839. dateEncoding: dateEncoding,
  840. nilEncoding: nilEncoding)
  841. return KeyedEncodingContainer(container)
  842. }
  843. func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
  844. defer { count += 1 }
  845. return _URLEncodedFormEncoder.UnkeyedContainer(context: context,
  846. codingPath: nestedCodingPath,
  847. boolEncoding: boolEncoding,
  848. dataEncoding: dataEncoding,
  849. dateEncoding: dateEncoding,
  850. nilEncoding: nilEncoding)
  851. }
  852. func superEncoder() -> Encoder {
  853. defer { count += 1 }
  854. return _URLEncodedFormEncoder(context: context,
  855. codingPath: codingPath,
  856. boolEncoding: boolEncoding,
  857. dataEncoding: dataEncoding,
  858. dateEncoding: dateEncoding,
  859. nilEncoding: nilEncoding)
  860. }
  861. }
  862. final class URLEncodedFormSerializer {
  863. private let alphabetizeKeyValuePairs: Bool
  864. private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding
  865. private let keyEncoding: URLEncodedFormEncoder.KeyEncoding
  866. private let keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding
  867. private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding
  868. private let allowedCharacters: CharacterSet
  869. init(alphabetizeKeyValuePairs: Bool,
  870. arrayEncoding: URLEncodedFormEncoder.ArrayEncoding,
  871. keyEncoding: URLEncodedFormEncoder.KeyEncoding,
  872. keyPathEncoding: URLEncodedFormEncoder.KeyPathEncoding,
  873. spaceEncoding: URLEncodedFormEncoder.SpaceEncoding,
  874. allowedCharacters: CharacterSet) {
  875. self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs
  876. self.arrayEncoding = arrayEncoding
  877. self.keyEncoding = keyEncoding
  878. self.keyPathEncoding = keyPathEncoding
  879. self.spaceEncoding = spaceEncoding
  880. self.allowedCharacters = allowedCharacters
  881. }
  882. func serialize(_ object: URLEncodedFormComponent.Object) -> String {
  883. var output: [String] = []
  884. for (key, component) in object {
  885. let value = serialize(component, forKey: key)
  886. output.append(value)
  887. }
  888. output = alphabetizeKeyValuePairs ? output.sorted() : output
  889. return output.joinedWithAmpersands()
  890. }
  891. func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String {
  892. switch component {
  893. case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(escape(string))"
  894. case let .array(array): return serialize(array, forKey: key)
  895. case let .object(object): return serialize(object, forKey: key)
  896. }
  897. }
  898. func serialize(_ object: URLEncodedFormComponent.Object, forKey key: String) -> String {
  899. var segments: [String] = object.map { subKey, value in
  900. let keyPath = keyPathEncoding.encodeKeyPath(subKey)
  901. return serialize(value, forKey: key + keyPath)
  902. }
  903. segments = alphabetizeKeyValuePairs ? segments.sorted() : segments
  904. return segments.joinedWithAmpersands()
  905. }
  906. func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String {
  907. var segments: [String] = array.enumerated().map { index, component in
  908. let keyPath = arrayEncoding.encode(key, atIndex: index)
  909. return serialize(component, forKey: keyPath)
  910. }
  911. segments = alphabetizeKeyValuePairs ? segments.sorted() : segments
  912. return segments.joinedWithAmpersands()
  913. }
  914. func escape(_ query: String) -> String {
  915. var allowedCharactersWithSpace = allowedCharacters
  916. allowedCharactersWithSpace.insert(charactersIn: " ")
  917. let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query
  918. let spaceEncodedQuery = spaceEncoding.encode(escapedQuery)
  919. return spaceEncodedQuery
  920. }
  921. }
  922. extension Array where Element == String {
  923. func joinedWithAmpersands() -> String {
  924. joined(separator: "&")
  925. }
  926. }
  927. extension CharacterSet {
  928. /// Creates a CharacterSet from RFC 3986 allowed characters.
  929. ///
  930. /// RFC 3986 states that the following characters are "reserved" characters.
  931. ///
  932. /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  933. /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  934. ///
  935. /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  936. /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  937. /// should be percent-escaped in the query string.
  938. public static let afURLQueryAllowed: CharacterSet = {
  939. let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
  940. let subDelimitersToEncode = "!$&'()*+,;="
  941. let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
  942. return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters)
  943. }()
  944. }