Validation.swift 6.7 KB

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