ParameterEncoder.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  1. //
  2. // ParameterEncoder.swift
  3. //
  4. // Copyright (c) 2014-2018 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. /// A type that can encode any `Encodable` type into a `URLRequest`.
  26. public protocol ParameterEncoder {
  27. /// Encode the provided `Encodable` parameters into `request`.
  28. ///
  29. /// - Parameters:
  30. /// - parameters: The `Encodable` parameter value.
  31. /// - request: The `URLRequest` into which to encode the parameters.
  32. /// - Returns: A `URLRequest` with the result of the encoding.
  33. /// - Throws: An `Error` when encoding fails. For Alamofire provided encoders, this will be an instance of
  34. /// `AFError.parameterEncoderFailed` with an associated `ParameterEncoderFailureReason`.
  35. func encode<Parameters: Encodable>(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest
  36. }
  37. /// A `ParameterEncoder` that encodes types as JSON body data.
  38. ///
  39. /// If no `Content-Type` header is already set on the provided `URLRequest`s, it's set to `application/json`.
  40. open class JSONParameterEncoder: ParameterEncoder {
  41. /// Returns an encoder with default parameters.
  42. public static var `default`: JSONParameterEncoder { return JSONParameterEncoder() }
  43. /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.prettyPrinted`.
  44. public static var prettyPrinted: JSONParameterEncoder {
  45. let encoder = JSONEncoder()
  46. encoder.outputFormatting = .prettyPrinted
  47. return JSONParameterEncoder(encoder: encoder)
  48. }
  49. /// Returns an encoder with `JSONEncoder.outputFormatting` set to `.sortedKeys`.
  50. @available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
  51. public static var sortedKeys: JSONParameterEncoder {
  52. let encoder = JSONEncoder()
  53. encoder.outputFormatting = .sortedKeys
  54. return JSONParameterEncoder(encoder: encoder)
  55. }
  56. /// `JSONEncoder` used to encode parameters.
  57. public let encoder: JSONEncoder
  58. /// Creates an instance with the provided `JSONEncoder`.
  59. ///
  60. /// - Parameter encoder: The `JSONEncoder`. Defaults to `JSONEncoder()`.
  61. public init(encoder: JSONEncoder = JSONEncoder()) {
  62. self.encoder = encoder
  63. }
  64. open func encode<Parameters: Encodable>(_ parameters: Parameters?,
  65. into request: URLRequest) throws -> URLRequest {
  66. guard let parameters = parameters else { return request }
  67. var request = request
  68. do {
  69. let data = try encoder.encode(parameters)
  70. request.httpBody = data
  71. if request.httpHeaders["Content-Type"] == nil {
  72. request.httpHeaders.update(.contentType("application/json"))
  73. }
  74. } catch {
  75. throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
  76. }
  77. return request
  78. }
  79. }
  80. /// A `ParameterEncoder` that encodes types as URL-encoded query strings to be set on the URL or as body data, depending
  81. /// on the `Destination` set.
  82. ///
  83. /// If no `Content-Type` header is already set on the provided `URLRequest`s, it will be set to
  84. /// `application/x-www-form-urlencoded; charset=utf-8`.
  85. ///
  86. /// There is no published specification for how to encode collection types. By default, the convention of appending
  87. /// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for
  88. /// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the
  89. /// square brackets appended to array keys.
  90. ///
  91. /// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode
  92. /// `true` as 1 and `false` as 0.
  93. open class URLEncodedFormParameterEncoder: ParameterEncoder {
  94. /// Defines where the URL-encoded string should be set for each `URLRequest`.
  95. public enum Destination {
  96. /// Applies the encoded query string to any existing query string for `.get`, `.head`, and `.delete` request.
  97. /// Sets it to the `httpBody` for all other methods.
  98. case methodDependent
  99. /// Applies the encoded query string to any existing query string from the `URLRequest`.
  100. case queryString
  101. /// Applies the encoded query string to the `httpBody` of the `URLRequest`.
  102. case httpBody
  103. /// Determines whether the URL-encoded string should be applied to the `URLRequest`'s `url`.
  104. ///
  105. /// - Parameter method: The `HTTPMethod`.
  106. /// - Returns: Whether the URL-encoded string should be applied to a `URL`.
  107. func encodesParametersInURL(for method: HTTPMethod) -> Bool {
  108. switch self {
  109. case .methodDependent: return [.get, .head, .delete].contains(method)
  110. case .queryString: return true
  111. case .httpBody: return false
  112. }
  113. }
  114. }
  115. /// Returns an encoder with default parameters.
  116. public static var `default`: URLEncodedFormParameterEncoder { return URLEncodedFormParameterEncoder() }
  117. /// The `URLEncodedFormEncoder` to use.
  118. public let encoder: URLEncodedFormEncoder
  119. /// The `Destination` for the URL-encoded string.
  120. public let destination: Destination
  121. /// Creates an instance with the provided `URLEncodedFormEncoder` instance and `Destination` value.
  122. ///
  123. /// - Parameters:
  124. /// - encoder: The `URLEncodedFormEncoder`. Defaults to `URLEncodedFormEncoder()`.
  125. /// - destination: The `Destination`. Defaults to `.methodDependent`.
  126. public init(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), destination: Destination = .methodDependent) {
  127. self.encoder = encoder
  128. self.destination = destination
  129. }
  130. open func encode<Parameters: Encodable>(_ parameters: Parameters?,
  131. into request: URLRequest) throws -> URLRequest {
  132. guard let parameters = parameters else { return request }
  133. var request = request
  134. guard let url = request.url else {
  135. throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url))
  136. }
  137. guard let rawMethod = request.httpMethod, let method = HTTPMethod(rawValue: rawMethod) else {
  138. let rawValue = request.httpMethod ?? "nil"
  139. throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.httpMethod(rawValue: rawValue)))
  140. }
  141. if destination.encodesParametersInURL(for: method),
  142. var components = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  143. let query: String = try AFResult<String> { try encoder.encode(parameters) }
  144. .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get()
  145. let newQueryString = [components.percentEncodedQuery, query].compactMap { $0 }.joinedWithAmpersands()
  146. components.percentEncodedQuery = newQueryString
  147. guard let newURL = components.url else {
  148. throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url))
  149. }
  150. request.url = newURL
  151. } else {
  152. if request.httpHeaders["Content-Type"] == nil {
  153. request.httpHeaders.update(.contentType("application/x-www-form-urlencoded; charset=utf-8"))
  154. }
  155. request.httpBody = try AFResult<Data> { try encoder.encode(parameters) }
  156. .mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get()
  157. }
  158. return request
  159. }
  160. }
  161. /// An object that encodes instances into URL-encoded query strings.
  162. ///
  163. /// There is no published specification for how to encode collection types. By default, the convention of appending
  164. /// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for
  165. /// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the
  166. /// square brackets appended to array keys.
  167. ///
  168. /// `BoolEncoding` can be used to configure how `Bool` values are encoded. The default behavior is to encode
  169. /// `true` as 1 and `false` as 0.
  170. ///
  171. /// `SpaceEncoding` can be used to configure how spaces are encoded. Modern encodings use percent replacement (%20),
  172. /// while older encoding may expect spaces to be replaced with +.
  173. ///
  174. /// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project.
  175. public final class URLEncodedFormEncoder {
  176. /// Configures how `Bool` parameters are encoded.
  177. public enum BoolEncoding {
  178. /// Encodes `true` as `1`, `false` as `0`.
  179. case numeric
  180. /// Encodes `true` as "true", `false` as "false".
  181. case literal
  182. /// Encodes the given `Bool` as a `String`.
  183. ///
  184. /// - Parameter value: The `Bool` to encode.
  185. /// - Returns: The encoded `String`.
  186. func encode(_ value: Bool) -> String {
  187. switch self {
  188. case .numeric: return value ? "1" : "0"
  189. case .literal: return value ? "true" : "false"
  190. }
  191. }
  192. }
  193. /// Configures how `Array` parameters are encoded.
  194. public enum ArrayEncoding {
  195. /// An empty set of square brackets ("[]") are sppended to the key for every value.
  196. case brackets
  197. /// No brackets are appended to the key and the key is encoded as is.
  198. case noBrackets
  199. func encode(_ key: String) -> String {
  200. switch self {
  201. case .brackets: return "\(key)[]"
  202. case .noBrackets: return key
  203. }
  204. }
  205. }
  206. /// Configures how spaces are encoded.
  207. public enum SpaceEncoding {
  208. /// Encodes spaces according to normal percent escaping rules (%20).
  209. case percentEscaped
  210. /// Encodes spaces as `+`,
  211. case plusReplaced
  212. /// Encodes the string according to the encoding.
  213. ///
  214. /// - Parameter string: The `String` to encode.
  215. /// - Returns: The encoded `String`.
  216. func encode(_ string: String) -> String {
  217. switch self {
  218. case .percentEscaped: return string.replacingOccurrences(of: " ", with: "%20")
  219. case .plusReplaced: return string.replacingOccurrences(of: " ", with: "+")
  220. }
  221. }
  222. }
  223. /// `URLEncodedFormEncoder` error.
  224. public enum Error: Swift.Error {
  225. /// An invalid root object was created by the encoder. Only keyed values are valid.
  226. case invalidRootObject(String)
  227. var localizedDescription: String {
  228. switch self {
  229. case let .invalidRootObject(object): return "URLEncodedFormEncoder requires keyed root object. Received \(object) instead."
  230. }
  231. }
  232. }
  233. /// The `ArrayEncoding` to use.
  234. public let arrayEncoding: ArrayEncoding
  235. /// The `BoolEncoding` to use.
  236. public let boolEncoding: BoolEncoding
  237. /// The `SpaceEncoding` to use.
  238. public let spaceEncoding: SpaceEncoding
  239. /// The `CharacterSet` of allowed characters.
  240. public var allowedCharacters: CharacterSet
  241. /// Creates an instance from the supplied parameters.
  242. ///
  243. /// - Parameters:
  244. /// - arrayEncoding: The `ArrayEncoding` instance. Defaults to `.brackets`.
  245. /// - boolEncoding: The `BoolEncoding` instance. Defaults to `.numeric`.
  246. /// - spaceEncoding: The `SpaceEncoding` instance. Defaults to `.percentEscaped`.
  247. /// - allowedCharacters: The `CharacterSet` of allowed (non-escaped) characters. Defaults to `.afURLQueryAllowed`.
  248. public init(arrayEncoding: ArrayEncoding = .brackets,
  249. boolEncoding: BoolEncoding = .numeric,
  250. spaceEncoding: SpaceEncoding = .percentEscaped,
  251. allowedCharacters: CharacterSet = .afURLQueryAllowed) {
  252. self.arrayEncoding = arrayEncoding
  253. self.boolEncoding = boolEncoding
  254. self.spaceEncoding = spaceEncoding
  255. self.allowedCharacters = allowedCharacters
  256. }
  257. func encode(_ value: Encodable) throws -> URLEncodedFormComponent {
  258. let context = URLEncodedFormContext(.object([:]))
  259. let encoder = _URLEncodedFormEncoder(context: context, boolEncoding: boolEncoding)
  260. try value.encode(to: encoder)
  261. return context.component
  262. }
  263. /// Encodes the `value` as a URL form encoded `String`.
  264. ///
  265. /// - Parameter value: The `Encodable` value.`
  266. /// - Returns: The encoded `String`.
  267. /// - Throws: An `Error` or `EncodingError` instance if encoding fails.
  268. public func encode(_ value: Encodable) throws -> String {
  269. let component: URLEncodedFormComponent = try encode(value)
  270. guard case let .object(object) = component else {
  271. throw Error.invalidRootObject("\(component)")
  272. }
  273. let serializer = URLEncodedFormSerializer(arrayEncoding: arrayEncoding,
  274. spaceEncoding: spaceEncoding,
  275. allowedCharacters: allowedCharacters)
  276. let query = serializer.serialize(object)
  277. return query
  278. }
  279. /// Encodes the value as `Data`. This is performed by first creating an encoded `String` and then returning the
  280. /// `.utf8` data.
  281. ///
  282. /// - Parameter value: The `Encodable` value.
  283. /// - Returns: The encoded `Data`.
  284. /// - Throws: An `Error` or `EncodingError` instance if encoding fails.
  285. public func encode(_ value: Encodable) throws -> Data {
  286. let string: String = try encode(value)
  287. return Data(string.utf8)
  288. }
  289. }
  290. final class _URLEncodedFormEncoder {
  291. var codingPath: [CodingKey]
  292. // Returns an empty dictionary, as this encoder doesn't support userInfo.
  293. var userInfo: [CodingUserInfoKey : Any] { return [:] }
  294. let context: URLEncodedFormContext
  295. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  296. public init(context: URLEncodedFormContext,
  297. codingPath: [CodingKey] = [],
  298. boolEncoding: URLEncodedFormEncoder.BoolEncoding) {
  299. self.context = context
  300. self.codingPath = codingPath
  301. self.boolEncoding = boolEncoding
  302. }
  303. }
  304. extension _URLEncodedFormEncoder: Encoder {
  305. func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey {
  306. let container = _URLEncodedFormEncoder.KeyedContainer<Key>(context: context,
  307. codingPath: codingPath,
  308. boolEncoding: boolEncoding)
  309. return KeyedEncodingContainer(container)
  310. }
  311. func unkeyedContainer() -> UnkeyedEncodingContainer {
  312. return _URLEncodedFormEncoder.UnkeyedContainer(context: context,
  313. codingPath: codingPath,
  314. boolEncoding: boolEncoding)
  315. }
  316. func singleValueContainer() -> SingleValueEncodingContainer {
  317. return _URLEncodedFormEncoder.SingleValueContainer(context: context,
  318. codingPath: codingPath,
  319. boolEncoding: boolEncoding)
  320. }
  321. }
  322. final class URLEncodedFormContext {
  323. var component: URLEncodedFormComponent
  324. init(_ component: URLEncodedFormComponent) {
  325. self.component = component
  326. }
  327. }
  328. enum URLEncodedFormComponent {
  329. case string(String)
  330. case array([URLEncodedFormComponent])
  331. case object([String: URLEncodedFormComponent])
  332. /// Converts self to an `[URLEncodedFormData]` or returns `nil` if not convertible.
  333. var array: [URLEncodedFormComponent]? {
  334. switch self {
  335. case let .array(array): return array
  336. default: return nil
  337. }
  338. }
  339. /// Converts self to an `[String: URLEncodedFormData]` or returns `nil` if not convertible.
  340. var object: [String: URLEncodedFormComponent]? {
  341. switch self {
  342. case let .object(object): return object
  343. default: return nil
  344. }
  345. }
  346. /// Sets self to the supplied value at a given path.
  347. ///
  348. /// data.set(to: "hello", at: ["path", "to", "value"])
  349. ///
  350. /// - parameters:
  351. /// - value: Value of `Self` to set at the supplied path.
  352. /// - path: `CodingKey` path to update with the supplied value.
  353. public mutating func set(to value: URLEncodedFormComponent, at path: [CodingKey]) {
  354. set(&self, to: value, at: path)
  355. }
  356. /// Recursive backing method to `set(to:at:)`.
  357. private func set(_ context: inout URLEncodedFormComponent, to value: URLEncodedFormComponent, at path: [CodingKey]) {
  358. guard path.count >= 1 else {
  359. context = value
  360. return
  361. }
  362. let end = path[0]
  363. var child: URLEncodedFormComponent
  364. switch path.count {
  365. case 1:
  366. child = value
  367. case 2...:
  368. if let index = end.intValue {
  369. let array = context.array ?? []
  370. if array.count > index {
  371. child = array[index]
  372. } else {
  373. child = .array([])
  374. }
  375. set(&child, to: value, at: Array(path[1...]))
  376. } else {
  377. child = context.object?[end.stringValue] ?? .object([:])
  378. set(&child, to: value, at: Array(path[1...]))
  379. }
  380. default: fatalError("Unreachable")
  381. }
  382. if let index = end.intValue {
  383. if var array = context.array {
  384. if array.count > index {
  385. array[index] = child
  386. } else {
  387. array.append(child)
  388. }
  389. context = .array(array)
  390. } else {
  391. context = .array([child])
  392. }
  393. } else {
  394. if var object = context.object {
  395. object[end.stringValue] = child
  396. context = .object(object)
  397. } else {
  398. context = .object([end.stringValue: child])
  399. }
  400. }
  401. }
  402. }
  403. struct AnyCodingKey: CodingKey, Hashable {
  404. let stringValue: String
  405. let intValue: Int?
  406. init?(stringValue: String) {
  407. self.stringValue = stringValue
  408. intValue = nil
  409. }
  410. init?(intValue: Int) {
  411. stringValue = "\(intValue)"
  412. self.intValue = intValue
  413. }
  414. init<Key>(_ base: Key) where Key : CodingKey {
  415. if let intValue = base.intValue {
  416. self.init(intValue: intValue)!
  417. } else {
  418. self.init(stringValue: base.stringValue)!
  419. }
  420. }
  421. }
  422. extension _URLEncodedFormEncoder {
  423. final class KeyedContainer<Key> where Key: CodingKey {
  424. var codingPath: [CodingKey]
  425. private let context: URLEncodedFormContext
  426. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  427. init(context: URLEncodedFormContext,
  428. codingPath: [CodingKey],
  429. boolEncoding: URLEncodedFormEncoder.BoolEncoding) {
  430. self.context = context
  431. self.codingPath = codingPath
  432. self.boolEncoding = boolEncoding
  433. }
  434. private func nestedCodingPath(for key: CodingKey) -> [CodingKey] {
  435. return codingPath + [key]
  436. }
  437. }
  438. }
  439. extension _URLEncodedFormEncoder.KeyedContainer: KeyedEncodingContainerProtocol {
  440. func encodeNil(forKey key: Key) throws {
  441. let context = EncodingError.Context(codingPath: codingPath,
  442. debugDescription: "URLEncodedFormEncoder cannot encode nil values.")
  443. throw EncodingError.invalidValue("\(key): nil", context)
  444. }
  445. func encode<T>(_ value: T, forKey key: Key) throws where T : Encodable {
  446. var container = nestedSingleValueEncoder(for: key)
  447. try container.encode(value)
  448. }
  449. func nestedSingleValueEncoder(for key: Key) -> SingleValueEncodingContainer {
  450. let container = _URLEncodedFormEncoder.SingleValueContainer(context: context,
  451. codingPath: nestedCodingPath(for: key),
  452. boolEncoding: boolEncoding)
  453. return container
  454. }
  455. func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
  456. let container = _URLEncodedFormEncoder.UnkeyedContainer(context: context,
  457. codingPath: nestedCodingPath(for: key),
  458. boolEncoding: boolEncoding)
  459. return container
  460. }
  461. func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
  462. let container = _URLEncodedFormEncoder.KeyedContainer<NestedKey>(context: context,
  463. codingPath: nestedCodingPath(for: key),
  464. boolEncoding: boolEncoding)
  465. return KeyedEncodingContainer(container)
  466. }
  467. func superEncoder() -> Encoder {
  468. return _URLEncodedFormEncoder(context: context, codingPath: codingPath, boolEncoding: boolEncoding)
  469. }
  470. func superEncoder(forKey key: Key) -> Encoder {
  471. return _URLEncodedFormEncoder(context: context, codingPath: nestedCodingPath(for: key), boolEncoding: boolEncoding)
  472. }
  473. }
  474. extension _URLEncodedFormEncoder {
  475. final class SingleValueContainer {
  476. var codingPath: [CodingKey]
  477. private var canEncodeNewValue = true
  478. private let context: URLEncodedFormContext
  479. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  480. init(context: URLEncodedFormContext, codingPath: [CodingKey], boolEncoding: URLEncodedFormEncoder.BoolEncoding) {
  481. self.context = context
  482. self.codingPath = codingPath
  483. self.boolEncoding = boolEncoding
  484. }
  485. private func checkCanEncode(value: Any?) throws {
  486. guard canEncodeNewValue else {
  487. let context = EncodingError.Context(codingPath: codingPath,
  488. debugDescription: "Attempt to encode value through single value container when previously value already encoded.")
  489. throw EncodingError.invalidValue(value as Any, context)
  490. }
  491. }
  492. }
  493. }
  494. extension _URLEncodedFormEncoder.SingleValueContainer: SingleValueEncodingContainer {
  495. func encodeNil() throws {
  496. try checkCanEncode(value: nil)
  497. defer { canEncodeNewValue = false }
  498. let context = EncodingError.Context(codingPath: codingPath,
  499. debugDescription: "URLEncodedFormEncoder cannot encode nil values.")
  500. throw EncodingError.invalidValue("nil", context)
  501. }
  502. func encode(_ value: Bool) throws {
  503. try encode(value, as: String(boolEncoding.encode(value)))
  504. }
  505. func encode(_ value: String) throws {
  506. try encode(value, as: value)
  507. }
  508. func encode(_ value: Double) throws {
  509. try encode(value, as: String(value))
  510. }
  511. func encode(_ value: Float) throws {
  512. try encode(value, as: String(value))
  513. }
  514. func encode(_ value: Int) throws {
  515. try encode(value, as: String(value))
  516. }
  517. func encode(_ value: Int8) throws {
  518. try encode(value, as: String(value))
  519. }
  520. func encode(_ value: Int16) throws {
  521. try encode(value, as: String(value))
  522. }
  523. func encode(_ value: Int32) throws {
  524. try encode(value, as: String(value))
  525. }
  526. func encode(_ value: Int64) throws {
  527. try encode(value, as: String(value))
  528. }
  529. func encode(_ value: UInt) throws {
  530. try encode(value, as: String(value))
  531. }
  532. func encode(_ value: UInt8) throws {
  533. try encode(value, as: String(value))
  534. }
  535. func encode(_ value: UInt16) throws {
  536. try encode(value, as: String(value))
  537. }
  538. func encode(_ value: UInt32) throws {
  539. try encode(value, as: String(value))
  540. }
  541. func encode(_ value: UInt64) throws {
  542. try encode(value, as: String(value))
  543. }
  544. private func encode<T>(_ value: T, as string: String) throws where T : Encodable {
  545. try checkCanEncode(value: value)
  546. defer { canEncodeNewValue = false }
  547. context.component.set(to: .string(string), at: codingPath)
  548. }
  549. func encode<T>(_ value: T) throws where T : Encodable {
  550. try checkCanEncode(value: value)
  551. defer { canEncodeNewValue = false }
  552. let encoder = _URLEncodedFormEncoder(context: context,
  553. codingPath: codingPath,
  554. boolEncoding: boolEncoding)
  555. try value.encode(to: encoder)
  556. }
  557. }
  558. extension _URLEncodedFormEncoder {
  559. final class UnkeyedContainer {
  560. var codingPath: [CodingKey]
  561. var count = 0
  562. var nestedCodingPath: [CodingKey] {
  563. return codingPath + [AnyCodingKey(intValue: count)!]
  564. }
  565. private let context: URLEncodedFormContext
  566. private let boolEncoding: URLEncodedFormEncoder.BoolEncoding
  567. init(context: URLEncodedFormContext,
  568. codingPath: [CodingKey],
  569. boolEncoding: URLEncodedFormEncoder.BoolEncoding) {
  570. self.context = context
  571. self.codingPath = codingPath
  572. self.boolEncoding = boolEncoding
  573. }
  574. }
  575. }
  576. extension _URLEncodedFormEncoder.UnkeyedContainer: UnkeyedEncodingContainer {
  577. func encodeNil() throws {
  578. let context = EncodingError.Context(codingPath: codingPath,
  579. debugDescription: "URLEncodedFormEncoder cannot encode nil values.")
  580. throw EncodingError.invalidValue("nil", context)
  581. }
  582. func encode<T>(_ value: T) throws where T : Encodable {
  583. var container = nestedSingleValueContainer()
  584. try container.encode(value)
  585. }
  586. func nestedSingleValueContainer() -> SingleValueEncodingContainer {
  587. defer { count += 1 }
  588. return _URLEncodedFormEncoder.SingleValueContainer(context: context,
  589. codingPath: nestedCodingPath,
  590. boolEncoding: boolEncoding)
  591. }
  592. func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
  593. defer { count += 1 }
  594. let container = _URLEncodedFormEncoder.KeyedContainer<NestedKey>(context: context,
  595. codingPath: nestedCodingPath,
  596. boolEncoding: boolEncoding)
  597. return KeyedEncodingContainer(container)
  598. }
  599. func nestedUnkeyedContainer() -> UnkeyedEncodingContainer {
  600. defer { count += 1 }
  601. return _URLEncodedFormEncoder.UnkeyedContainer(context: context,
  602. codingPath: nestedCodingPath,
  603. boolEncoding: boolEncoding)
  604. }
  605. func superEncoder() -> Encoder {
  606. defer { count += 1 }
  607. return _URLEncodedFormEncoder(context: context, codingPath: codingPath, boolEncoding: boolEncoding)
  608. }
  609. }
  610. final class URLEncodedFormSerializer {
  611. let arrayEncoding: URLEncodedFormEncoder.ArrayEncoding
  612. let spaceEncoding: URLEncodedFormEncoder.SpaceEncoding
  613. let allowedCharacters: CharacterSet
  614. init(arrayEncoding: URLEncodedFormEncoder.ArrayEncoding,
  615. spaceEncoding: URLEncodedFormEncoder.SpaceEncoding,
  616. allowedCharacters: CharacterSet) {
  617. self.arrayEncoding = arrayEncoding
  618. self.spaceEncoding = spaceEncoding
  619. self.allowedCharacters = allowedCharacters
  620. }
  621. func serialize(_ object: [String: URLEncodedFormComponent]) -> String {
  622. var output: [String] = []
  623. for (key, component) in object {
  624. let value = serialize(component, forKey: key)
  625. output.append(value)
  626. }
  627. return output.joinedWithAmpersands()
  628. }
  629. func serialize(_ component: URLEncodedFormComponent, forKey key: String) -> String {
  630. switch component {
  631. case let .string(string): return "\(escape(key))=\(escape(string))"
  632. case let .array(array): return serialize(array, forKey: key)
  633. case let .object(dictionary): return serialize(dictionary, forKey: key)
  634. }
  635. }
  636. func serialize(_ object: [String: URLEncodedFormComponent], forKey key: String) -> String {
  637. let segments: [String] = object.map { (subKey, value) in
  638. let keyPath = "[\(subKey)]"
  639. return serialize(value, forKey: key + keyPath)
  640. }
  641. return segments.joinedWithAmpersands()
  642. }
  643. func serialize(_ array: [URLEncodedFormComponent], forKey key: String) -> String {
  644. let segments: [String] = array.map { (component) in
  645. let keyPath = arrayEncoding.encode(key)
  646. return serialize(component, forKey: keyPath)
  647. }
  648. return segments.joinedWithAmpersands()
  649. }
  650. func escape(_ query: String) -> String {
  651. var allowedCharactersWithSpace = allowedCharacters
  652. allowedCharactersWithSpace.insert(charactersIn: " ")
  653. let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharactersWithSpace) ?? query
  654. let spaceEncodedQuery = spaceEncoding.encode(escapedQuery)
  655. return spaceEncodedQuery
  656. }
  657. }
  658. extension Array where Element == String {
  659. func joinedWithAmpersands() -> String {
  660. return joined(separator: "&")
  661. }
  662. }
  663. extension CharacterSet {
  664. /// Creates a CharacterSet from RFC 3986 allowed characters.
  665. ///
  666. /// RFC 3986 states that the following characters are "reserved" characters.
  667. ///
  668. /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
  669. /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
  670. ///
  671. /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
  672. /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
  673. /// should be percent-escaped in the query string.
  674. public static let afURLQueryAllowed: CharacterSet = {
  675. let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
  676. let subDelimitersToEncode = "!$&'()*+,;="
  677. let encodableDelimiters = CharacterSet(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
  678. return CharacterSet.urlQueryAllowed.subtracting(encodableDelimiters)
  679. }()
  680. }