Slather logo

Coverage for "InterceptorMultiplexer.swift" : 100.00%

(37 of 37 relevant lines covered)

RouteComposer/Classes/Router/Multiplexers/InterceptorMultiplexer.swift

1
//
2
// RouteComposer
3
// InterceptorMultiplexer.swift
4
// https://github.com/ekazaev/route-composer
5
//
6
// Created by Eugene Kazaev in 2018-2022.
7
// Distributed under the MIT license.
8
//
9
// Become a sponsor:
10
// https://github.com/sponsors/ekazaev
11
//
12
13
import Foundation
14
15
struct InterceptorMultiplexer: AnyRoutingInterceptor, MainThreadChecking, CustomStringConvertible {
16
17
    private var interceptors: [AnyRoutingInterceptor]
18
19
    init(_ interceptors: [AnyRoutingInterceptor]) {
6x
20
        self.interceptors = interceptors
6x
21
    }
6x
22
23
    mutating func prepare(with context: AnyContext) throws {
6x
24
        interceptors = try interceptors.map {
6x
25
            var interceptor = $0
6x
26
            try interceptor.prepare(with: context)
6x
27
            return interceptor
6x
28
        }
6x
29
    }
6x
30
31
    func perform(with context: AnyContext, completion: @escaping (RoutingResult) -> Void) {
4x
32
        guard !self.interceptors.isEmpty else {
4x
33
            completion(.success)
1x
34
            return
1x
35
        }
3x
36
3x
37
        var interceptors = interceptors
3x
38
3x
39
        func runInterceptor(interceptor: AnyRoutingInterceptor) {
3x
40
            assertIfNotMainThread()
3x
41
            interceptor.perform(with: context) { result in
3x
42
                self.assertIfNotMainThread()
3x
43
                if case .failure = result {
3x
44
                    completion(result)
2x
45
                } else if interceptors.isEmpty {
3x
46
                    completion(result)
1x
47
                } else {
3x
48
                    runInterceptor(interceptor: interceptors.removeFirst())
2x
49
                }
3x
50
            }
3x
51
        }
3x
52
3x
53
        runInterceptor(interceptor: interceptors.removeFirst())
3x
54
    }
3x
55
56
    var description: String {
1x
57
        String(describing: interceptors)
1x
58
    }
1x
59
60
}