This repository has been archived by the owner on Nov 16, 2020. It is now read-only.
/
URLEncodedFormDecoder.swift
304 lines (258 loc) 路 11.2 KB
/
URLEncodedFormDecoder.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
/// Decodes instances of `Decodable` types from `application/x-www-form-urlencoded` `Data`.
///
/// print(data) // "name=Vapor&age=3"
/// let user = try URLEncodedFormDecoder().decode(User.self, from: data)
/// print(user) // User
///
/// URL-encoded forms are commonly used by websites to send form data via POST requests. This encoding is relatively
/// efficient for small amounts of data but must be percent-encoded. `multipart/form-data` is more efficient for sending
/// large data blobs like files.
///
/// See [Mozilla's](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) docs for more information about
/// url-encoded forms.
public final class URLEncodedFormDecoder: DataDecoder {
/// The underlying `URLEncodedFormEncodedParser`
private let parser: URLEncodedFormParser
/// If `true`, empty values will be omitted. Empty values are URL-Encoded keys with no value following the `=` sign.
///
/// name=Vapor&age=
///
/// In the above example, `age` is an empty value.
public var omitEmptyValues: Bool
/// If `true`, flags will be omitted. Flags are URL-encoded keys with no following `=` sign.
///
/// name=Vapor&isAdmin&age=3
///
/// In the above example, `isAdmin` is a flag.
public var omitFlags: Bool
/// Create a new `URLEncodedFormDecoder`.
///
/// - parameters:
/// - omitEmptyValues: If `true`, empty values will be omitted.
/// Empty values are URL-Encoded keys with no value following the `=` sign.
/// - omitFlags: If `true`, flags will be omitted.
/// Flags are URL-encoded keys with no following `=` sign.
public init(omitEmptyValues: Bool = false, omitFlags: Bool = false) {
self.parser = URLEncodedFormParser()
self.omitFlags = omitFlags
self.omitEmptyValues = omitEmptyValues
}
/// Decodes an instance of the supplied `Decodable` type from `Data`.
///
/// print(data) // "name=Vapor&age=3"
/// let user = try URLEncodedFormDecoder().decode(User.self, from: data)
/// print(user) // User
///
/// - parameters:
/// - decodable: Generic `Decodable` type (`D`) to decode.
/// - from: `Data` to decode a `D` from.
/// - returns: An instance of the `Decodable` type (`D`).
/// - throws: Any error that may occur while attempting to decode the specified type.
public func decode<D>(_ decodable: D.Type, from data: Data) throws -> D where D : Decodable {
let urlEncodedFormData = try self.parser.parse(percentEncoded: String(data: data, encoding: .utf8) ?? "", omitEmptyValues: self.omitEmptyValues, omitFlags: self.omitFlags)
let decoder = _URLEncodedFormDecoder(context: .init(.dict(urlEncodedFormData)), codingPath: [])
return try D(from: decoder)
}
}
// MARK: Private
/// Private `Decoder`. See `URLEncodedFormDecoder` for public decoder.
private final class _URLEncodedFormDecoder: Decoder {
/// See `Decoder`
let codingPath: [CodingKey]
/// See `Decoder`
var userInfo: [CodingUserInfoKey: Any] {
return [:]
}
/// The data being decoded
let context: URLEncodedFormDataContext
/// Creates a new `_URLEncodedFormDecoder`.
init(context: URLEncodedFormDataContext, codingPath: [CodingKey]) {
self.context = context
self.codingPath = codingPath
}
/// See `Decoder`
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key>
where Key: CodingKey
{
return .init(_URLEncodedFormKeyedDecoder<Key>(context: context, codingPath: codingPath))
}
/// See `Decoder`
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
return _URLEncodedFormUnkeyedDecoder(context: context, codingPath: codingPath)
}
/// See `Decoder`
func singleValueContainer() throws -> SingleValueDecodingContainer {
return _URLEncodedFormSingleValueDecoder(context: context, codingPath: codingPath)
}
}
/// Private `SingleValueDecodingContainer`.
private final class _URLEncodedFormSingleValueDecoder: SingleValueDecodingContainer {
/// The data being decoded
let context: URLEncodedFormDataContext
/// See `SingleValueDecodingContainer`
var codingPath: [CodingKey]
/// Creates a new `_URLEncodedFormSingleValueDecoder`.
init(context: URLEncodedFormDataContext, codingPath: [CodingKey]) {
self.context = context
self.codingPath = codingPath
}
/// See `SingleValueDecodingContainer`
func decodeNil() -> Bool {
return context.data.get(at: codingPath) == nil
}
/// See `SingleValueDecodingContainer`
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
guard let data = context.data.get(at: codingPath) else {
throw DecodingError.valueNotFound(T.self, at: codingPath)
}
if let convertible = T.self as? URLEncodedFormDataConvertible.Type {
return try convertible.convertFromURLEncodedFormData(data) as! T
} else {
let decoder = _URLEncodedFormDecoder(context: context, codingPath: codingPath)
return try T.init(from: decoder)
}
}
}
/// Private `KeyedDecodingContainerProtocol`.
private final class _URLEncodedFormKeyedDecoder<K>: KeyedDecodingContainerProtocol where K: CodingKey {
/// See `KeyedDecodingContainerProtocol.`
typealias Key = K
/// The data being decoded
let context: URLEncodedFormDataContext
/// See `KeyedDecodingContainerProtocol.`
var codingPath: [CodingKey]
/// See `KeyedDecodingContainerProtocol.`
var allKeys: [K] {
guard let dictionary = context.data.get(at: codingPath)?.dictionary else {
return []
}
return dictionary.keys.compactMap { K(stringValue: $0) }
}
/// Create a new `_URLEncodedFormKeyedDecoder`
init(context: URLEncodedFormDataContext, codingPath: [CodingKey]) {
self.context = context
self.codingPath = codingPath
}
/// See `KeyedDecodingContainerProtocol.`
func contains(_ key: K) -> Bool {
return context.data.get(at: codingPath)?.dictionary?[key.stringValue] != nil
}
/// See `KeyedDecodingContainerProtocol.`
func decodeNil(forKey key: K) throws -> Bool {
return context.data.get(at: codingPath + [key]) == nil
}
/// See `KeyedDecodingContainerProtocol.`
func decode<T>(_ type: T.Type, forKey key: K) throws -> T where T: Decodable {
if let convertible = T.self as? URLEncodedFormDataConvertible.Type {
guard let data = context.data.get(at: codingPath + [key]) else {
throw DecodingError.valueNotFound(T.self, at: codingPath + [key])
}
return try convertible.convertFromURLEncodedFormData(data) as! T
} else {
let decoder = _URLEncodedFormDecoder(context: context, codingPath: codingPath + [key])
return try T(from: decoder)
}
}
/// See `KeyedDecodingContainerProtocol.`
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: K) throws -> KeyedDecodingContainer<NestedKey>
where NestedKey: CodingKey
{
return .init(_URLEncodedFormKeyedDecoder<NestedKey>(context: context, codingPath: codingPath + [key]))
}
/// See `KeyedDecodingContainerProtocol.`
func nestedUnkeyedContainer(forKey key: K) throws -> UnkeyedDecodingContainer {
return _URLEncodedFormUnkeyedDecoder(context: context, codingPath: codingPath + [key])
}
/// See `KeyedDecodingContainerProtocol.`
func superDecoder() throws -> Decoder {
return _URLEncodedFormDecoder(context: context, codingPath: codingPath)
}
/// See `KeyedDecodingContainerProtocol.`
func superDecoder(forKey key: K) throws -> Decoder {
return _URLEncodedFormDecoder(context: context, codingPath: codingPath + [key])
}
}
/// Private `UnkeyedDecodingContainer`.
private final class _URLEncodedFormUnkeyedDecoder: UnkeyedDecodingContainer {
/// The data being decoded
let context: URLEncodedFormDataContext
/// See `UnkeyedDecodingContainer`.
var codingPath: [CodingKey]
/// See `UnkeyedDecodingContainer`.
var count: Int? {
guard let array = context.data.get(at: codingPath)?.array else {
return nil
}
return array.count
}
/// See `UnkeyedDecodingContainer`.
var isAtEnd: Bool {
guard let count = self.count else {
return true
}
return currentIndex >= count
}
/// See `UnkeyedDecodingContainer`.
var currentIndex: Int
/// Converts the current index to a coding key
var index: CodingKey {
return BasicKey(currentIndex)
}
/// Create a new `_URLEncodedFormUnkeyedDecoder`
init(context: URLEncodedFormDataContext, codingPath: [CodingKey]) {
self.context = context
self.codingPath = codingPath
currentIndex = 0
}
/// See `UnkeyedDecodingContainer`.
func decodeNil() throws -> Bool {
return context.data.get(at: codingPath + [index]) == nil
}
/// See `UnkeyedDecodingContainer`.
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
defer { currentIndex += 1 }
if let convertible = T.self as? URLEncodedFormDataConvertible.Type {
guard let data = context.data.get(at: codingPath + [index]) else {
throw DecodingError.valueNotFound(T.self, at: codingPath + [index])
}
return try convertible.convertFromURLEncodedFormData(data) as! T
} else {
let decoder = _URLEncodedFormDecoder(context: context, codingPath: codingPath + [index])
return try T(from: decoder)
}
}
/// See `UnkeyedDecodingContainer`.
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey>
where NestedKey: CodingKey
{
return .init(_URLEncodedFormKeyedDecoder<NestedKey>(context: context, codingPath: codingPath + [index]))
}
/// See `UnkeyedDecodingContainer`.
func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
return _URLEncodedFormUnkeyedDecoder(context: context, codingPath: codingPath + [index])
}
/// See `UnkeyedDecodingContainer`.
func superDecoder() throws -> Decoder {
defer { currentIndex += 1 }
return _URLEncodedFormDecoder(context: context, codingPath: codingPath + [index])
}
}
// MARK: Utils
private extension DecodingError {
static func typeMismatch(_ type: Any.Type, at path: [CodingKey]) -> DecodingError {
let pathString = path.map { $0.stringValue }.joined(separator: ".")
let context = DecodingError.Context(
codingPath: path,
debugDescription: "No \(type) was found at path \(pathString)"
)
return Swift.DecodingError.typeMismatch(type, context)
}
static func valueNotFound(_ type: Any.Type, at path: [CodingKey]) -> DecodingError {
let pathString = path.map { $0.stringValue }.joined(separator: ".")
let context = DecodingError.Context(
codingPath: path,
debugDescription: "No \(type) was found at path \(pathString)"
)
return Swift.DecodingError.valueNotFound(type, context)
}
}