URLEncodedFormEncoder.swift 40 KB

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