URLEncodedFormEncoder.swift 45 KB

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