commonMain.ru.astrainteractive.klibs.mikro.validation.impl.ValidationContextImpl.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mikro-validation Show documentation
Show all versions of mikro-validation Show documentation
Kotlin Multiplatform library with useful code
The newest version!
package ru.astrainteractive.klibs.mikro.validation.impl
import ru.astrainteractive.klibs.mikro.validation.Validation
import ru.astrainteractive.klibs.mikro.validation.ValidationContext
import ru.astrainteractive.klibs.mikro.validation.Validator
import ru.astrainteractive.klibs.mikro.validation.ValidatorResult
internal class ValidationContextImpl(override val value: T) : ValidationContext {
private data class ValidationData(
val validation: Validation,
val violdation: R,
val index: Int
)
private var i = 0
private val validations = mutableListOf>()
override fun validate(otherwise: (T) -> R, validation: Validation): Validation {
val otherwiseResult = otherwise.invoke(value)
return validate(otherwiseResult, validation)
}
override fun validate(otherwise: R, validation: Validation): Validation {
val data = ValidationData(
validation = validation,
violdation = otherwise,
index = i++
)
validations.add(data)
return validation
}
override fun create(): List> {
return validations
.sortedBy { it.index }
.map { validationData ->
Validator { value ->
val isValid = validationData.validation.validate(value)
if (isValid) {
ValidatorResult.Success
} else {
ValidatorResult.Failure(validationData.violdation)
}
}
}
}
}