URLEncodedFormEncoder.swift 39 KB

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