commonMain.io.konform.validation.internal.Validation.kt Maven / Gradle / Ivy
package io.konform.validation.internal
import io.konform.validation.Constraint
import io.konform.validation.Invalid
import io.konform.validation.Valid
import io.konform.validation.Validation
import io.konform.validation.ValidationResult
import kotlin.reflect.KProperty1
internal class NonNullPropertyValidation(
private val property: KProperty1,
private val validation: Validation
) : Validation {
override fun validate(value: T): ValidationResult {
val propertyValue = property(value)
return validation(propertyValue).mapError { ".${property.name}$it" }.map { value }
}
}
internal class OptionalPropertyValidation(
private val property: KProperty1,
private val validation: Validation
) : Validation {
override fun validate(value: T): ValidationResult {
val propertyValue = property(value) ?: return Valid(value)
return validation(propertyValue).mapError { ".${property.name}$it" }.map { value }
}
}
internal class RequiredPropertyValidation(
private val property: KProperty1,
private val validation: Validation
) : Validation {
override fun validate(value: T): ValidationResult {
val propertyValue = property(value)
?: return Invalid(mapOf(".${property.name}" to listOf("is required")))
return validation(propertyValue).mapError { ".${property.name}${it}" }.map { value }
}
}
internal class IterableValidation(
private val validation: Validation
) : Validation> {
override fun validate(value: Iterable): ValidationResult> {
return value.foldIndexed(Valid(value)) { index, result: ValidationResult>, propertyValue ->
val propertyValidation = validation(propertyValue).mapError { "[$index]$it" }.map { value }
result.combineWith(propertyValidation)
}
}
}
internal class ArrayValidation(
private val validation: Validation
) : Validation> {
override fun validate(value: Array): ValidationResult> {
return value.foldIndexed(Valid(value)) { index, result: ValidationResult>, propertyValue ->
val propertyValidation = validation(propertyValue).mapError { "[$index]$it" }.map { value }
result.combineWith(propertyValidation)
}
}
}
internal class MapValidation(
private val validation: Validation>
) : Validation