Validation.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. //
  2. // Validation.swift
  3. //
  4. // Copyright (c) 2014-2016 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. extension Request {
  26. /**
  27. Used to represent whether validation was successful or encountered an error resulting in a failure.
  28. - Success: The validation was successful.
  29. - Failure: The validation failed encountering the provided error.
  30. */
  31. public enum ValidationResult {
  32. case success
  33. case failure(NSError)
  34. }
  35. /**
  36. A closure used to validate a request that takes a URL request and URL response, and returns whether the
  37. request was valid.
  38. */
  39. public typealias Validation = (Foundation.URLRequest?, HTTPURLResponse) -> ValidationResult
  40. /**
  41. Validates the request, using the specified closure.
  42. If validation fails, subsequent calls to response handlers will have an associated error.
  43. - parameter validation: A closure to validate the request.
  44. - returns: The request.
  45. */
  46. public func validate(_ validation: Validation) -> Self {
  47. delegate.queue.addOperation {
  48. if let
  49. response = self.response where self.delegate.error == nil,
  50. case let .failure(error) = validation(self.request, response)
  51. {
  52. self.delegate.error = error
  53. }
  54. }
  55. return self
  56. }
  57. // MARK: - Status Code
  58. /**
  59. Validates that the response has a status code in the specified range.
  60. If validation fails, subsequent calls to response handlers will have an associated error.
  61. - parameter range: The range of acceptable status codes.
  62. - returns: The request.
  63. */
  64. public func validate<S: Sequence where S.Iterator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
  65. return validate { _, response in
  66. if acceptableStatusCode.contains(response.statusCode) {
  67. return .success
  68. } else {
  69. let failureReason = "Response status code was unacceptable: \(response.statusCode)"
  70. let error = NSError(
  71. domain: Error.Domain,
  72. code: Error.Code.statusCodeValidationFailed.rawValue,
  73. userInfo: [
  74. NSLocalizedFailureReasonErrorKey: failureReason,
  75. Error.UserInfoKeys.StatusCode: response.statusCode
  76. ]
  77. )
  78. return .failure(error)
  79. }
  80. }
  81. }
  82. // MARK: - Content-Type
  83. private struct MIMEType {
  84. let type: String
  85. let subtype: String
  86. init?(_ string: String) {
  87. let components: [String] = {
  88. let stripped = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
  89. let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)
  90. return split.components(separatedBy: "/")
  91. }()
  92. if let
  93. type = components.first,
  94. subtype = components.last
  95. {
  96. self.type = type
  97. self.subtype = subtype
  98. } else {
  99. return nil
  100. }
  101. }
  102. func matches(_ MIME: MIMEType) -> Bool {
  103. switch (type, subtype) {
  104. case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
  105. return true
  106. default:
  107. return false
  108. }
  109. }
  110. }
  111. /**
  112. Validates that the response has a content type in the specified array.
  113. If validation fails, subsequent calls to response handlers will have an associated error.
  114. - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  115. - returns: The request.
  116. */
  117. public func validate<S : Sequence where S.Iterator.Element == String>(contentType acceptableContentTypes: S) -> Self {
  118. return validate { _, response in
  119. guard let validData = self.delegate.data where validData.count > 0 else { return .success }
  120. if let
  121. responseContentType = response.mimeType,
  122. responseMIMEType = MIMEType(responseContentType)
  123. {
  124. for contentType in acceptableContentTypes {
  125. if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) {
  126. return .success
  127. }
  128. }
  129. } else {
  130. for contentType in acceptableContentTypes {
  131. if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" {
  132. return .success
  133. }
  134. }
  135. }
  136. let contentType: String
  137. let failureReason: String
  138. if let responseContentType = response.mimeType {
  139. contentType = responseContentType
  140. failureReason = (
  141. "Response content type \"\(responseContentType)\" does not match any acceptable " +
  142. "content types: \(acceptableContentTypes)"
  143. )
  144. } else {
  145. contentType = ""
  146. failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
  147. }
  148. let error = NSError(
  149. domain: Error.Domain,
  150. code: Error.Code.contentTypeValidationFailed.rawValue,
  151. userInfo: [
  152. NSLocalizedFailureReasonErrorKey: failureReason,
  153. Error.UserInfoKeys.ContentType: contentType
  154. ]
  155. )
  156. return .failure(error)
  157. }
  158. }
  159. // MARK: - Automatic
  160. /**
  161. Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  162. type matches any specified in the Accept HTTP header field.
  163. If validation fails, subsequent calls to response handlers will have an associated error.
  164. - returns: The request.
  165. */
  166. public func validate() -> Self {
  167. let acceptableStatusCodes: CountableRange<Int> = 200..<300
  168. let acceptableContentTypes: [String] = {
  169. if let accept = request?.value(forHTTPHeaderField: "Accept") {
  170. return accept.components(separatedBy: ",")
  171. }
  172. return ["*/*"]
  173. }()
  174. return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
  175. }
  176. }