URLEncodedFormEncoder.swift 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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 appended 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. convert(key, usingSeparator: "_")
  196. }
  197. private func convertToKebabCase(_ key: String) -> String {
  198. 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):
  273. return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead."
  274. }
  275. }
  276. }
  277. /// Whether or not to sort the encoded key value pairs.
  278. ///
  279. /// - Note: This setting ensures a consistent ordering for all encodings of the same parameters. When set to `false`,
  280. /// encoded `Dictionary` values may have a different encoded order each time they're encoded due to
  281. /// ` Dictionary`'s random storage order, but `Encodable` types will maintain their encoded order.
  282. public let alphabetizeKeyValuePairs: Bool
  283. /// The `ArrayEncoding` to use.
  284. public let arrayEncoding: ArrayEncoding
  285. /// The `BoolEncoding` to use.
  286. public let boolEncoding: BoolEncoding
  287. /// THe `DataEncoding` to use.
  288. public let dataEncoding: DataEncoding
  289. /// The `DateEncoding` to use.
  290. public let dateEncoding: DateEncoding
  291. /// The `KeyEncoding` to use.
  292. public let keyEncoding: KeyEncoding
  293. /// The `SpaceEncoding` to use.
  294. public let spaceEncoding: SpaceEncoding
  295. /// The `CharacterSet` of allowed (non-escaped) characters.
  296. public var allowedCharacters: CharacterSet
  297. /// Creates an instance from the supplied parameters.
  298. ///
  299. /// - Parameters:
  300. /// - alphabetizeKeyValuePairs: Whether or not to sort the encoded key value pairs. `true` by default.
  301. /// - arrayEncoding: The `ArrayEncoding` to use. `.brackets` by default.
  302. /// - boolEncoding: The `BoolEncoding` to use. `.numeric` by default.
  303. /// - dataEncoding: The `DataEncoding` to use. `.base64` by default.
  304. /// - dateEncoding: The `DateEncoding` to use. `.deferredToDate` by default.
  305. /// - keyEncoding: The `KeyEncoding` to use. `.useDefaultKeys` by default.
  306. /// - spaceEncoding: The `SpaceEncoding` to use. `.percentEscaped` by default.
  307. /// - allowedCharacters: The `CharacterSet` of allowed (non-escaped) characters. `.afURLQueryAllowed` by
  308. /// default.
  309. public init(alphabetizeKeyValuePairs: Bool = true,
  310. arrayEncoding: ArrayEncoding = .brackets,
  311. boolEncoding: BoolEncoding = .numeric,
  312. dataEncoding: DataEncoding = .base64,
  313. dateEncoding: DateEncoding = .deferredToDate,
  314. keyEncoding: KeyEncoding = .useDefaultKeys,
  315. spaceEncoding: SpaceEncoding = .percentEscaped,
  316. allowedCharacters: CharacterSet = .afURLQueryAllowed)
  317. {
  318. self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs
  319. self.arrayEncoding = arrayEncoding
  320. self.boolEncoding = boolEncoding
  321. self.dataEncoding = dataEncoding
  322. self.dateEncoding = dateEncoding
  323. self.keyEncoding = keyEncoding
  324. self.spaceEncoding = spaceEncoding
  325. self.allowedCharacters = allowedCharacters
  326. }
  327. func encode(_ value: Encodable) throws -> URLEncodedFormComponent {
  328. let context = URLEncodedFormContext(.object([]))
  329. let encoder = _URLEncodedFormEncoder(context: context,
  330. boolEncoding: boolEncoding,
  331. dataEncoding: dataEncoding,
  332. dateEncoding: dateEncoding)
  333. try value.encode(to: encoder)
  334. return context.component
  335. }
  336. /// Encodes the `value` as a URL form encoded `String`.
  337. ///
  338. /// - Parameter value: The `Encodable` value.`
  339. ///
  340. /// - Returns: The encoded `String`.
  341. /// - Throws: An `Error` or `EncodingError` instance if encoding fails.
  342. public func encode(_ value: Encodable) throws -> String {
  343. let component: URLEncodedFormComponent = try encode(value)
  344. guard case let .object(object) = component else {
  345. throw Error.invalidRootObject("\(component)")
  346. }
  347. let serializer = URLEncodedFormSerializer(alphabetizeKeyValuePairs: alphabetizeKeyValuePairs,
  348. arrayEncoding: arrayEncoding,
  349. keyEncoding: keyEncoding,
  350. spaceEncoding: spaceEncoding,
  351. allowedCharacters: allowedCharacters)
  352. let query = serializer.serialize(object)
  353. return query
  354. }
  355. /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the
  356. /// `.utf8` data.
  357. ///
  358. /// - Parameter value: The `Encodable` value.
  359. ///
  360. /// - Returns: The encoded `Data`.
  361. ///
  362. /// - Throws: An `Error` or `EncodingError` instance if encoding fails.
  363. public func encode(_ value: Encodable) throws -> Data {
  364. let string: String = try encode(value)
  365. return Data(string.utf8)
  366. }
  367. }
  368. final class _URLEncodedFormEncoder {
  369. var codingPath: [CodingKey]
  370. // Returns an empty dictionary, as this encoder doesn't support userInfo.
  371. var userInfo: [CodingUserInfoKey: Any] { [:] }
  372. let context: URLEncodedFormContext
  373. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  374. private let dataEncoding: URLEncodedFormEncoder.DataEncoding
  375. private let dateEncoding: URLEncodedFormEncoder.DateEncoding
  376. init(context: URLEncodedFormContext,
  377. codingPath: [CodingKey] = [],
  378. boolEncoding: URLEncodedFormEncoder.BoolEncoding,
  379. dataEncoding: URLEncodedFormEncoder.DataEncoding,
  380. dateEncoding: URLEncodedFormEncoder.DateEncoding)
  381. {
  382. self.context = context
  383. self.codingPath = codingPath
  384. self.boolEncoding = boolEncoding
  385. self.dataEncoding = dataEncoding
  386. self.dateEncoding = dateEncoding
  387. }
  388. }
  389. extension _URLEncodedFormEncoder: Encoder {
  390. func container<Key>(keyedBy _: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
  391. let container = _URLEncodedFormEncoder.KeyedContainer<Key>(context: context,
  392. codingPath: codingPath,
  393. boolEncoding: boolEncoding,
  394. dataEncoding: dataEncoding,
  395. dateEncoding: dateEncoding)
  396. return KeyedEncodingContainer(container)
  397. }
  398. func unkeyedContainer() -> UnkeyedEncodingContainer {
  399. _URLEncodedFormEncoder.UnkeyedContainer(context: context,
  400. codingPath: codingPath,
  401. boolEncoding: boolEncoding,
  402. dataEncoding: dataEncoding,
  403. dateEncoding: dateEncoding)
  404. }
  405. func singleValueContainer() -> SingleValueEncodingContainer {
  406. _URLEncodedFormEncoder.SingleValueContainer(context: context,
  407. codingPath: codingPath,
  408. boolEncoding: boolEncoding,
  409. dataEncoding: dataEncoding,
  410. dateEncoding: dateEncoding)
  411. }
  412. }
  413. final class URLEncodedFormContext {
  414. var component: URLEncodedFormComponent
  415. init(_ component: URLEncodedFormComponent) {
  416. self.component = component
  417. }
  418. }
  419. enum URLEncodedFormComponent {
  420. typealias Object = [(key: String, value: URLEncodedFormComponent)]
  421. case string(String)
  422. case array([URLEncodedFormComponent])
  423. case object(Object)
  424. /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible.
  425. var array: [URLEncodedFormComponent]? {
  426. switch self {
  427. case let .array(array): return array
  428. default: return nil
  429. }
  430. }
  431. /// Converts self to an `Object` or returns `nil` if not convertible.
  432. var object: Object? {
  433. switch self {
  434. case let .object(object): return object
  435. default: return nil
  436. }
  437. }
  438. /// Sets self to the supplied value at a given path.
  439. ///
  440. /// data.set(to: "hello", at: ["path", "to", "value"])
  441. ///
  442. /// - parameters:
  443. /// - value: Value of `Self` to set at the supplied path.
  444. /// - path: `CodingKey` path to update with the supplied value.
  445. public mutating func set(to value: URLEncodedFormComponent, at path: [CodingKey]) {
  446. set(&self, to: value, at: path)
  447. }
  448. /// Recursive backing method to `set(to:at:)`.
  449. private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [CodingKey]) {
  450. guard !path.isEmpty else {
  451. context = value
  452. return
  453. }
  454. let end = path[0]
  455. var child: URLEncodedFormComponent
  456. switch path.count {
  457. case 1:
  458. child = value
  459. case 2...:
  460. if let index = end.intValue {
  461. let array = context.array ?? []
  462. if array.count > index {
  463. child = array[index]
  464. } else {
  465. child = .array([])
  466. }
  467. set(&child, to: value, at: Array(path[1...]))
  468. } else {
  469. child = context.object?.first { $0.key == end.stringValue }?.value ?? .object(.init())
  470. set(&child, to: value, at: Array(path[1...]))
  471. }
  472. default: fatalError("Unreachable")
  473. }
  474. if let index = end.intValue {
  475. if var array = context.array {
  476. if array.count > index {
  477. array[index] = child
  478. } else {
  479. array.append(child)
  480. }
  481. context = .array(array)
  482. } else {
  483. context = .array([child])
  484. }
  485. } else {
  486. if var object = context.object {
  487. if let index = object.firstIndex(where: { $0.key == end.stringValue }) {
  488. object[index] = (key: end.stringValue, value: child)
  489. } else {
  490. object.append((key: end.stringValue, value: child))
  491. }
  492. context = .object(object)
  493. } else {
  494. context = .object([(key: end.stringValue, value: child)])
  495. }
  496. }
  497. }
  498. }
  499. struct AnyCodingKey: CodingKey, Hashable {
  500. let stringValue: String
  501. let intValue: Int?
  502. init?(stringValue: String) {
  503. self.stringValue = stringValue
  504. intValue = nil
  505. }
  506. init?(intValue: Int) {
  507. stringValue = "\(intValue)"
  508. self.intValue = intValue
  509. }
  510. init<Key>(_ base: Key) where Key: CodingKey {
  511. if let intValue = base.intValue {
  512. self.init(intValue: intValue)!
  513. } else {
  514. self.init(stringValue: base.stringValue)!
  515. }
  516. }
  517. }
  518. extension _URLEncodedFormEncoder {
  519. final class KeyedContainer<Key> where Key: CodingKey {
  520. var codingPath: [CodingKey]
  521. private let context: URLEncodedFormContext
  522. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  523. private let dataEncoding: URLEncodedFormEncoder.DataEncoding
  524. private let dateEncoding: URLEncodedFormEncoder.DateEncoding
  525. init(context: URLEncodedFormContext,
  526. codingPath: [CodingKey],
  527. boolEncoding: URLEncodedFormEncoder.BoolEncoding,
  528. dataEncoding: URLEncodedFormEncoder.DataEncoding,
  529. dateEncoding: URLEncodedFormEncoder.DateEncoding)
  530. {
  531. self.context = context
  532. self.codingPath = codingPath
  533. self.boolEncoding = boolEncoding
  534. self.dataEncoding = dataEncoding
  535. self.dateEncoding = dateEncoding
  536. }
  537. private func nestedCodingPath(for key: CodingKey) -> [CodingKey] {
  538. codingPath + [key]
  539. }
  540. }
  541. }
  542. extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol {
  543. func encodeNil(forKey key: Key) throws {
  544. let context = EncodingError.Context(codingPath: codingPath,
  545. debugDescription: "URLEncodedFormEncoder cannot encode nil values.")
  546. throw EncodingError.invalidValue("\(key): nil", context)
  547. }
  548. func encode<T>(_ value: T, forKey key: Key) throws where T: Encodable {
  549. var container = nestedSingleValueEncoder(for: key)
  550. try container.encode(value)
  551. }
  552. func nestedSingleValueEncoder(for key: Key) -> SingleValueEncodingContainer {
  553. let container = _URLEncodedFormEncoder.SingleValueContainer(context: context,
  554. codingPath: nestedCodingPath(for: key),
  555. boolEncoding: boolEncoding,
  556. dataEncoding: dataEncoding,
  557. dateEncoding: dateEncoding)
  558. return container
  559. }
  560. func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
  561. let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context,
  562. codingPath: nestedCodingPath(for: key),
  563. boolEncoding: boolEncoding,
  564. dataEncoding: dataEncoding,
  565. dateEncoding: dateEncoding)
  566. return container
  567. }
  568. func nestedContainer<NestedKey>(keyedBy _: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
  569. let container = _URLEncodedFormEncoder.KeyedContainer<NestedKey>(context: context,
  570. codingPath: nestedCodingPath(for: key),
  571. boolEncoding: boolEncoding,
  572. dataEncoding: dataEncoding,
  573. dateEncoding: dateEncoding)
  574. return KeyedEncodingContainer(container)
  575. }
  576. func superEncoder() -> Encoder {
  577. _URLEncodedFormEncoder(context: context,
  578. codingPath: codingPath,
  579. boolEncoding: boolEncoding,
  580. dataEncoding: dataEncoding,
  581. dateEncoding: dateEncoding)
  582. }
  583. func superEncoder(forKey key: Key) -> Encoder {
  584. _URLEncodedFormEncoder(context: context,
  585. codingPath: nestedCodingPath(for: key),
  586. boolEncoding: boolEncoding,
  587. dataEncoding: dataEncoding,
  588. dateEncoding: dateEncoding)
  589. }
  590. }
  591. extension _URLEncodedFormEncoder {
  592. final class SingleValueContainer {
  593. var codingPath: [CodingKey]
  594. private var canEncodeNewValue = true
  595. private let context: URLEncodedFormContext
  596. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  597. private let dataEncoding: URLEncodedFormEncoder.DataEncoding
  598. private let dateEncoding: URLEncodedFormEncoder.DateEncoding
  599. init(context: URLEncodedFormContext,
  600. codingPath: [CodingKey],
  601. boolEncoding: URLEncodedFormEncoder.BoolEncoding,
  602. dataEncoding: URLEncodedFormEncoder.DataEncoding,
  603. dateEncoding: URLEncodedFormEncoder.DateEncoding)
  604. {
  605. self.context = context
  606. self.codingPath = codingPath
  607. self.boolEncoding = boolEncoding
  608. self.dataEncoding = dataEncoding
  609. self.dateEncoding = dateEncoding
  610. }
  611. private func checkCanEncode(value: Any?) throws {
  612. guard canEncodeNewValue else {
  613. let context = EncodingError.Context(codingPath: codingPath,
  614. debugDescription: "Attempt to encode value through single value container when previously value already encoded.")
  615. throw EncodingError.invalidValue(value as Any, context)
  616. }
  617. }
  618. }
  619. }
  620. extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer {
  621. func encodeNil() throws {
  622. try checkCanEncode(value: nil)
  623. defer { canEncodeNewValue = false }
  624. let context = EncodingError.Context(codingPath: codingPath,
  625. debugDescription: "URLEncodedFormEncoder cannot encode nil values.")
  626. throw EncodingError.invalidValue("nil", context)
  627. }
  628. func encode(_ value: Bool) throws {
  629. try encode(value, as: String(boolEncoding.encode(value)))
  630. }
  631. func encode(_ value: String) throws {
  632. try encode(value, as: value)
  633. }
  634. func encode(_ value: Double) throws {
  635. try encode(value, as: String(value))
  636. }
  637. func encode(_ value: Float) throws {
  638. try encode(value, as: String(value))
  639. }
  640. func encode(_ value: Int) throws {
  641. try encode(value, as: String(value))
  642. }
  643. func encode(_ value: Int8) throws {
  644. try encode(value, as: String(value))
  645. }
  646. func encode(_ value: Int16) throws {
  647. try encode(value, as: String(value))
  648. }
  649. func encode(_ value: Int32) throws {
  650. try encode(value, as: String(value))
  651. }
  652. func encode(_ value: Int64) throws {
  653. try encode(value, as: String(value))
  654. }
  655. func encode(_ value: UInt) throws {
  656. try encode(value, as: String(value))
  657. }
  658. func encode(_ value: UInt8) throws {
  659. try encode(value, as: String(value))
  660. }
  661. func encode(_ value: UInt16) throws {
  662. try encode(value, as: String(value))
  663. }
  664. func encode(_ value: UInt32) throws {
  665. try encode(value, as: String(value))
  666. }
  667. func encode(_ value: UInt64) throws {
  668. try encode(value, as: String(value))
  669. }
  670. private func encode<T>(_ value: T, as string: String) throws where T: Encodable {
  671. try checkCanEncode(value: value)
  672. defer { canEncodeNewValue = false }
  673. context.component.set(to: .string(string), at: codingPath)
  674. }
  675. func encode<T>(_ value: T) throws where T: Encodable {
  676. switch value {
  677. case let date as Date:
  678. guard let string = try dateEncoding.encode(date) else {
  679. try attemptToEncode(value)
  680. return
  681. }
  682. try encode(value, as: string)
  683. case let data as Data:
  684. guard let string = try dataEncoding.encode(data) else {
  685. try attemptToEncode(value)
  686. return
  687. }
  688. try encode(value, as: string)
  689. case let decimal as Decimal:
  690. // Decimal's `Encodable` implementation returns an object, not a single value, so override it.
  691. try encode(value, as: String(describing: decimal))
  692. default:
  693. try attemptToEncode(value)
  694. }
  695. }
  696. private func attemptToEncode<T>(_ value: T) throws where T: Encodable {
  697. try checkCanEncode(value: value)
  698. defer { canEncodeNewValue = false }
  699. let encoder = _URLEncodedFormEncoder(context: context,
  700. codingPath: codingPath,
  701. boolEncoding: boolEncoding,
  702. dataEncoding: dataEncoding,
  703. dateEncoding: dateEncoding)
  704. try value.encode(to: encoder)
  705. }
  706. }
  707. extension _URLEncodedFormEncoder {
  708. final class UnkeyedContainer {
  709. var codingPath: [CodingKey]
  710. var count = 0
  711. var nestedCodingPath: [CodingKey] {
  712. codingPath + [AnyCodingKey(intValue: count)!]
  713. }
  714. private let context: URLEncodedFormContext
  715. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  716. private let dataEncoding: URLEncodedFormEncoder.DataEncoding
  717. private let dateEncoding: URLEncodedFormEncoder.DateEncoding
  718. init(context: URLEncodedFormContext,
  719. codingPath: [CodingKey],
  720. boolEncoding: URLEncodedFormEncoder.BoolEncoding,
  721. dataEncoding: URLEncodedFormEncoder.DataEncoding,
  722. dateEncoding: URLEncodedFormEncoder.DateEncoding)
  723. {
  724. self.context = context
  725. self.codingPath = codingPath
  726. self.boolEncoding = boolEncoding
  727. self.dataEncoding = dataEncoding
  728. self.dateEncoding = dateEncoding
  729. }
  730. }
  731. }
  732. extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer {
  733. func encodeNil() throws {
  734. let context = EncodingError.Context(codingPath: codingPath,
  735. debugDescription: "URLEncodedFormEncoder cannot encode nil values.")
  736. throw EncodingError.invalidValue("nil", context)
  737. }
  738. func encode<T>(_ value: T) throws where T: Encodable {
  739. var container = nestedSingleValueContainer()
  740. try container.encode(value)
  741. }
  742. func nestedSingleValueContainer() -> SingleValueEncodingContainer {
  743. defer { count += 1 }
  744. return _URLEncodedFormEncoder.SingleValueContainer(context: context,
  745. codingPath: nestedCodingPath,
  746. boolEncoding: boolEncoding,
  747. dataEncoding: dataEncoding,
  748. dateEncoding: dateEncoding)
  749. }
  750. func nestedContainer<NestedKey>(keyedBy _: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey {
  751. defer { count += 1 }
  752. let container = _URLEncodedFormEncoder.KeyedContainer<NestedKey>(context: context,
  753. codingPath: nestedCodingPath,
  754. boolEncoding: boolEncoding,
  755. dataEncoding: dataEncoding,
  756. dateEncoding: dateEncoding)
  757. return KeyedEncodingContainer(container)
  758. }
  759. func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
  760. defer { count += 1 }
  761. return _URLEncodedFormEncoder.UnkeyedContainer(context: context,
  762. codingPath: nestedCodingPath,
  763. boolEncoding: boolEncoding,
  764. dataEncoding: dataEncoding,
  765. dateEncoding: dateEncoding)
  766. }
  767. func superEncoder() -> Encoder {
  768. defer { count += 1 }
  769. return _URLEncodedFormEncoder(context: context,
  770. codingPath: codingPath,
  771. boolEncoding: boolEncoding,
  772. dataEncoding: dataEncoding,
  773. dateEncoding: dateEncoding)
  774. }
  775. }
  776. final class URLEncodedFormSerializer {
  777. private let alphabetizeKeyValuePairs: Bool
  778. private let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding
  779. private let keyEncoding: URLEncodedFormEncoder.KeyEncoding
  780. private let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding
  781. private let allowedCharacters: CharacterSet
  782. init(alphabetizeKeyValuePairs: Bool,
  783. arrayEncoding: URLEncodedFormEncoder.ArrayEncoding,
  784. keyEncoding: URLEncodedFormEncoder.KeyEncoding,
  785. spaceEncoding: URLEncodedFormEncoder.SpaceEncoding,
  786. allowedCharacters: CharacterSet)
  787. {
  788. self.alphabetizeKeyValuePairs = alphabetizeKeyValuePairs
  789. self.arrayEncoding = arrayEncoding
  790. self.keyEncoding = keyEncoding
  791. self.spaceEncoding = spaceEncoding
  792. self.allowedCharacters = allowedCharacters
  793. }
  794. func serialize(_ object: URLEncodedFormComponent.Object) -> String {
  795. var output: [String] = []
  796. for (key, component) in object {
  797. let value = serialize(component, forKey: key)
  798. output.append(value)
  799. }
  800. output = alphabetizeKeyValuePairs ? output.sorted() : output
  801. return output.joinedWithAmpersands()
  802. }
  803. func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String {
  804. switch component {
  805. case let .string(string): return "\(escape(keyEncoding.encode(key)))=\(escape(string))"
  806. case let .array(array): return serialize(array, forKey: key)
  807. case let .object(object): return serialize(object, forKey: key)
  808. }
  809. }
  810. func serialize(_ object: URLEncodedFormComponent.Object, forKey key: String) -> String {
  811. var segments: [String] = object.map { subKey, value in
  812. let keyPath = "[\(subKey)]"
  813. return serialize(value, forKey: key + keyPath)
  814. }
  815. segments = alphabetizeKeyValuePairs ? segments.sorted() : segments
  816. return segments.joinedWithAmpersands()
  817. }
  818. func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String {
  819. var segments: [String] = array.map { component in
  820. let keyPath = arrayEncoding.encode(key)
  821. return serialize(component, forKey: keyPath)
  822. }
  823. segments = alphabetizeKeyValuePairs ? segments.sorted() : segments
  824. return segments.joinedWithAmpersands()
  825. }
  826. func escape(_ query: String) -> String {
  827. var allowedCharactersWithSpace = allowedCharacters
  828. allowedCharactersWithSpace.insert(charactersIn: " ")
  829. let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query
  830. let spaceEncodedQuery = spaceEncoding.encode(escapedQuery)
  831. return spaceEncodedQuery
  832. }
  833. }
  834. extension Array where Element == String {
  835. func joinedWithAmpersands() -> String {
  836. joined(separator: "&")
  837. }
  838. }
  839. public extension CharacterSet {
  840. /// Creates a CharacterSet from RFC 3986 allowed characters.
  841. ///
  842. /// RFC 3986 states that the following characters are "reserved" characters.
  843. ///
  844. /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  845. /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  846. ///
  847. /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  848. /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  849. /// should be percent-escaped in the query string.
  850. static let afURLQueryAllowed: CharacterSet = {
  851. let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
  852. let subDelimitersToEncode = "!$&'()*+,;="
  853. let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
  854. return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters)
  855. }()
  856. }