Validation.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. // Validation.swift
  2. //
  3. // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. extension Request {
  24. /**
  25. Used to represent whether validation was successful or encountered an error resulting in a failure.
  26. - Success: The validation was successful.
  27. - Failure: The validation failed encountering the provided error.
  28. */
  29. public enum ValidationResult {
  30. case Success
  31. case Failure(NSError)
  32. }
  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. */
  37. public typealias Validation = (NSURLRequest?, NSHTTPURLResponse) -> ValidationResult
  38. /**
  39. Validates the request, using the specified closure.
  40. If validation fails, subsequent calls to response handlers will have an associated error.
  41. - parameter validation: A closure to validate the request.
  42. - returns: The request.
  43. */
  44. public func validate(validation: Validation) -> Self {
  45. delegate.queue.addOperationWithBlock {
  46. if let
  47. response = self.response where self.delegate.error == nil,
  48. case let .Failure(error) = validation(self.request, response)
  49. {
  50. self.delegate.error = error
  51. }
  52. }
  53. return self
  54. }
  55. // MARK: - Status Code
  56. /**
  57. Validates that the response has a status code in the specified range.
  58. If validation fails, subsequent calls to response handlers will have an associated error.
  59. - parameter range: The range of acceptable status codes.
  60. - returns: The request.
  61. */
  62. public func validate<S: SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
  63. return validate { _, response in
  64. if acceptableStatusCode.contains(response.statusCode) {
  65. return .Success
  66. } else {
  67. let failureReason = "Response status code was unacceptable: \(response.statusCode)"
  68. return .Failure(Error.errorWithCode(.StatusCodeValidationFailed, failureReason: failureReason))
  69. }
  70. }
  71. }
  72. // MARK: - Content-Type
  73. private struct MIMEType {
  74. let type: String
  75. let subtype: String
  76. init?(_ string: String) {
  77. let components: [String] = {
  78. let stripped = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
  79. let split = stripped.substringToIndex(stripped.rangeOfString(";")?.startIndex ?? stripped.endIndex)
  80. return split.componentsSeparatedByString("/")
  81. }()
  82. if let
  83. type = components.first,
  84. subtype = components.last
  85. {
  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. /**
  102. Validates that the response has a content type in the specified array.
  103. If validation fails, subsequent calls to response handlers will have an associated error.
  104. - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  105. - returns: The request.
  106. */
  107. public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
  108. return validate { _, response in
  109. guard let validData = self.delegate.data where validData.length > 0 else { return .Success }
  110. if let
  111. responseContentType = response.MIMEType,
  112. responseMIMEType = MIMEType(responseContentType)
  113. {
  114. for contentType in acceptableContentTypes {
  115. if let acceptableMIMEType = MIMEType(contentType) where acceptableMIMEType.matches(responseMIMEType) {
  116. return .Success
  117. }
  118. }
  119. } else {
  120. for contentType in acceptableContentTypes {
  121. if let MIMEType = MIMEType(contentType) where MIMEType.type == "*" && MIMEType.subtype == "*" {
  122. return .Success
  123. }
  124. }
  125. }
  126. let failureReason: String
  127. if let responseContentType = response.MIMEType {
  128. failureReason = (
  129. "Response content type \"\(responseContentType)\" does not match any acceptable " +
  130. "content types: \(acceptableContentTypes)"
  131. )
  132. } else {
  133. failureReason = "Response content type was missing and acceptable content type does not match \"*/*\""
  134. }
  135. return .Failure(Error.errorWithCode(.ContentTypeValidationFailed, failureReason: failureReason))
  136. }
  137. }
  138. // MARK: - Automatic
  139. /**
  140. Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  141. type matches any specified in the Accept HTTP header field.
  142. If validation fails, subsequent calls to response handlers will have an associated error.
  143. - returns: The request.
  144. */
  145. public func validate() -> Self {
  146. let acceptableStatusCodes: Range<Int> = 200..<300
  147. let acceptableContentTypes: [String] = {
  148. if let accept = request?.valueForHTTPHeaderField("Accept") {
  149. return accept.componentsSeparatedByString(",")
  150. }
  151. return ["*/*"]
  152. }()
  153. return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
  154. }
  155. }