forked from ReactiveCocoa/ReactiveSwift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidatingProperty.swift
325 lines (283 loc) · 9.72 KB
/
ValidatingProperty.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/// A mutable property that validates mutations before committing them.
///
/// If the property wraps an arbitrary mutable property, changes originated from
/// the inner property are monitored, and would be automatically validated.
/// Note that these would still appear as committed values even if they fail the
/// validation.
///
/// ```
/// let root = MutableProperty("Valid")
/// let outer = ValidatingProperty(root) {
/// $0 == "Valid" ? .valid : .invalid(.outerInvalid)
/// }
///
/// outer.result.value // `.valid("Valid")
///
/// root.value = "🎃"
/// outer.result.value // `.invalid("🎃", .outerInvalid)`
/// ```
public final class ValidatingProperty<Value, ValidationError: Swift.Error>: MutablePropertyProtocol {
private let getter: () -> Value
private let setter: (Value) -> Void
/// The result of the last attempted edit of the root property.
public let result: Property<Result>
/// The current value of the property.
///
/// The value could have failed the validation. Refer to `result` for the
/// latest validation result.
public var value: Value {
get { return getter() }
set { setter(newValue) }
}
/// A producer for Signals that will send the property's current value,
/// followed by all changes over time, then complete when the property has
/// deinitialized.
public let producer: SignalProducer<Value, Never>
/// A signal that will send the property's changes over time,
/// then complete when the property has deinitialized.
public let signal: Signal<Value, Never>
/// The lifetime of the property.
public let lifetime: Lifetime
/// Create a `ValidatingProperty` that presents a mutable validating
/// view for an inner mutable property.
///
/// The proposed value is only committed when `valid` is returned by the
/// `validator` closure.
///
/// - note: `inner` is retained by the created property.
///
/// - parameters:
/// - inner: The inner property which validated values are committed to.
/// - validator: The closure to invoke for any proposed value to `self`.
public init<Inner: ComposableMutablePropertyProtocol>(
_ inner: Inner,
_ validator: @escaping (Value) -> Decision
) where Inner.Value == Value {
getter = { inner.value }
producer = inner.producer
signal = inner.signal
lifetime = inner.lifetime
// This flag temporarily suspends the monitoring on the inner property for
// writebacks that are triggered by successful validations.
var isSettingInnerValue = false
(result, setter) = inner.withValue { initial in
let mutableResult = MutableProperty(Result(initial, validator(initial)))
mutableResult <~ inner.signal
.filter { _ in !isSettingInnerValue }
.map { Result($0, validator($0)) }
return (Property(capturing: mutableResult), { input in
// Acquire the lock of `inner` to ensure no modification happens until
// the validation logic here completes.
inner.withValue { _ in
let writebackValue: Value? = mutableResult.modify { result in
result = Result(input, validator(input))
return result.value
}
if let value = writebackValue {
isSettingInnerValue = true
inner.value = value
isSettingInnerValue = false
}
}
})
}
}
/// Create a `ValidatingProperty` that validates mutations before
/// committing them.
///
/// The proposed value is only committed when `valid` is returned by the
/// `validator` closure.
///
/// - parameters:
/// - initial: The initial value of the property. It is not required to
/// pass the validation as specified by `validator`.
/// - validator: The closure to invoke for any proposed value to `self`.
public convenience init(
_ initial: Value,
_ validator: @escaping (Value) -> Decision
) {
self.init(MutableProperty(initial), validator)
}
/// Create a `ValidatingProperty` that presents a mutable validating
/// view for an inner mutable property.
///
/// The proposed value is only committed when `valid` is returned by the
/// `validator` closure.
///
/// - note: `inner` is retained by the created property.
///
/// - parameters:
/// - inner: The inner property which validated values are committed to.
/// - other: The property that `validator` depends on.
/// - validator: The closure to invoke for any proposed value to `self`.
public convenience init<Other: PropertyProtocol>(
_ inner: MutableProperty<Value>,
with other: Other,
_ validator: @escaping (Value, Other.Value) -> Decision
) {
// Capture a copy that reflects `other` without influencing the lifetime of
// `other`.
let other = Property(other)
self.init(inner) { input in
return validator(input, other.value)
}
// When `other` pushes out a new value, the resulting property would react
// by revalidating itself with its last attempted value, regardless of
// success or failure.
other.signal
.take(during: lifetime)
.observeValues { [weak self] _ in
guard let s = self else { return }
switch s.result.value {
case let .invalid(value, _):
s.value = value
case let .coerced(_, value, _):
s.value = value
case let .valid(value):
s.value = value
}
}
}
/// Create a `ValidatingProperty` that validates mutations before
/// committing them.
///
/// The proposed value is only committed when `valid` is returned by the
/// `validator` closure.
///
/// - parameters:
/// - initial: The initial value of the property. It is not required to
/// pass the validation as specified by `validator`.
/// - other: The property that `validator` depends on.
/// - validator: The closure to invoke for any proposed value to `self`.
public convenience init<Other: PropertyProtocol>(
_ initial: Value,
with other: Other,
_ validator: @escaping (Value, Other.Value) -> Decision
) {
self.init(MutableProperty(initial), with: other, validator)
}
/// Create a `ValidatingProperty` which validates mutations before
/// committing them.
///
/// The proposed value is only committed when `valid` is returned by the
/// `validator` closure.
///
/// - note: `inner` is retained by the created property.
///
/// - parameters:
/// - initial: The initial value of the property. It is not required to
/// pass the validation as specified by `validator`.
/// - other: The property that `validator` depends on.
/// - validator: The closure to invoke for any proposed value to `self`.
public convenience init<U, E>(
_ initial: Value,
with other: ValidatingProperty<U, E>,
_ validator: @escaping (Value, U) -> Decision
) {
self.init(MutableProperty(initial), with: other, validator)
}
/// Create a `ValidatingProperty` that presents a mutable validating
/// view for an inner mutable property.
///
/// The proposed value is only committed when `valid` is returned by the
/// `validator` closure.
///
/// - parameters:
/// - inner: The inner property which validated values are committed to.
/// - other: The property that `validator` depends on.
/// - validator: The closure to invoke for any proposed value to `self`.
public convenience init<U, E>(
_ inner: MutableProperty<Value>,
with other: ValidatingProperty<U, E>,
_ validator: @escaping (Value, U) -> Decision
) {
// Capture only `other.result` but not `other`.
let otherValidations = other.result
self.init(inner) { input in
let otherValue: U
switch otherValidations.value {
case let .valid(value):
otherValue = value
case let .coerced(_, value, _):
otherValue = value
case let .invalid(value, _):
otherValue = value
}
return validator(input, otherValue)
}
// When `other` pushes out a new validation result, the resulting property
// would react by revalidating itself with its last attempted value,
// regardless of success or failure.
otherValidations.signal
.take(during: lifetime)
.observeValues { [weak self] _ in
guard let s = self else { return }
switch s.result.value {
case let .invalid(value, _):
s.value = value
case let .coerced(_, value, _):
s.value = value
case let .valid(value):
s.value = value
}
}
}
/// Represents a decision of a validator of a validating property made on a
/// proposed value.
public enum Decision {
/// The proposed value is valid.
case valid
/// The proposed value is invalid, but the validator coerces it into a
/// replacement which it deems valid.
case coerced(Value, ValidationError?)
/// The proposed value is invalid.
case invalid(ValidationError)
}
/// Represents the result of the validation performed by a validating property.
public enum Result {
/// The proposed value is valid.
case valid(Value)
/// The proposed value is invalid, but the validator was able to coerce it
/// into a replacement which it deemed valid.
case coerced(replacement: Value, proposed: Value, error: ValidationError?)
/// The proposed value is invalid.
case invalid(Value, ValidationError)
/// Whether the value is invalid.
public var isInvalid: Bool {
if case .invalid = self {
return true
} else {
return false
}
}
/// Extract the valid value, or `nil` if the value is invalid.
public var value: Value? {
switch self {
case let .valid(value):
return value
case let .coerced(value, _, _):
return value
case .invalid:
return nil
}
}
/// Extract the error if the value is invalid.
public var error: ValidationError? {
if case let .invalid(_, error) = self {
return error
} else {
return nil
}
}
fileprivate init(_ value: Value, _ decision: Decision) {
switch decision {
case .valid:
self = .valid(value)
case let .coerced(replacement, error):
self = .coerced(replacement: replacement, proposed: value, error: error)
case let .invalid(error):
self = .invalid(value, error)
}
}
}
}