Validation.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. /// Used to represent whether validation was successful or encountered an error resulting in a failure.
  27. ///
  28. /// - success: The validation was successful.
  29. /// - failure: The validation failed encountering the provided error.
  30. public enum ValidationResult {
  31. case success
  32. case failure(Error)
  33. }
  34. /// A closure used to validate a request that takes a URL request and URL response, and returns whether the
  35. /// request was valid.
  36. public typealias Validation = (URLRequest?, HTTPURLResponse) -> ValidationResult
  37. /// Validates the request, using the specified closure.
  38. ///
  39. /// If validation fails, subsequent calls to response handlers will have an associated error.
  40. ///
  41. /// - parameter validation: A closure to validate the request.
  42. ///
  43. /// - returns: The request.
  44. @discardableResult
  45. public func validate(_ validation: Validation) -> Self {
  46. delegate.queue.addOperation {
  47. if
  48. let response = self.response,
  49. 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. /// Validates that the response has a status code in the specified range.
  59. ///
  60. /// If validation fails, subsequent calls to response handlers will have an associated error.
  61. ///
  62. /// - parameter range: The range of acceptable status codes.
  63. ///
  64. /// - returns: The request.
  65. @discardableResult
  66. public func validate<S: Sequence>(statusCode acceptableStatusCode: S) -> Self where S.Iterator.Element == Int {
  67. return validate { _, response in
  68. if acceptableStatusCode.contains(response.statusCode) {
  69. return .success
  70. } else {
  71. return .failure(AFError.responseValidationFailed(reason: .unacceptableStatusCode(code: response.statusCode)))
  72. }
  73. }
  74. }
  75. // MARK: - Content-Type
  76. private struct MIMEType {
  77. let type: String
  78. let subtype: String
  79. init?(_ string: String) {
  80. let components: [String] = {
  81. let stripped = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
  82. let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)
  83. return split.components(separatedBy: "/")
  84. }()
  85. if let type = components.first, let subtype = components.last {
  86. self.type = type
  87. self.subtype = subtype
  88. } else {
  89. return nil
  90. }
  91. }
  92. func matches(_ mime: MIMEType) -> Bool {
  93. switch (type, subtype) {
  94. case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"):
  95. return true
  96. default:
  97. return false
  98. }
  99. }
  100. }
  101. /// Validates that the response has a content type in the specified array.
  102. ///
  103. /// If validation fails, subsequent calls to response handlers will have an associated error.
  104. ///
  105. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  106. ///
  107. /// - returns: The request.
  108. @discardableResult
  109. public func validate<S: Sequence>(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String {
  110. return validate { _, response in
  111. guard let validData = self.delegate.data, validData.count > 0 else { return .success }
  112. guard
  113. let responseContentType = response.mimeType,
  114. let responseMIMEType = MIMEType(responseContentType) else {
  115. for contentType in acceptableContentTypes {
  116. if let mimeType = MIMEType(contentType), mimeType.type == "*" && mimeType.subtype == "*" {
  117. return .success
  118. }
  119. }
  120. return .failure(AFError.responseValidationFailed(reason: .missingContentType(acceptableContentTypes: Array(acceptableContentTypes))))
  121. }
  122. for contentType in acceptableContentTypes {
  123. if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
  124. return .success
  125. }
  126. }
  127. let error = AFError.responseValidationFailed(reason: .unacceptableContentType(acceptableContentTypes: Array(acceptableContentTypes), responseContentType: responseContentType))
  128. return .failure(error)
  129. }
  130. }
  131. // MARK: - Automatic
  132. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  133. /// type matches any specified in the Accept HTTP header field.
  134. ///
  135. /// If validation fails, subsequent calls to response handlers will have an associated error.
  136. ///
  137. /// - returns: The request.
  138. @discardableResult
  139. public func validate() -> Self {
  140. let acceptableStatusCodes: CountableRange<Int> = 200..<300
  141. let acceptableContentTypes: [String] = {
  142. if let accept = request?.value(forHTTPHeaderField: "Accept") {
  143. return accept.components(separatedBy: ",")
  144. }
  145. return ["*/*"]
  146. }()
  147. return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
  148. }
  149. }