commonMain.com.javiersc.kotlin.stdlib.validate.Validator.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kotlin-stdlib Show documentation
Show all versions of kotlin-stdlib Show documentation
Adds missing features in the official Kotlin stdlib
The newest version!
package com.javiersc.kotlin.stdlib.validate
import com.javiersc.kotlin.stdlib.Either
import com.javiersc.kotlin.stdlib.UseContextParameters
public class Validator
@PublishedApi
internal constructor(
@PublishedApi internal val name: String,
@PublishedApi internal val block: ValidatorScope.(V) -> Unit,
) {
public inline fun validate(value: A): Either {
val validatorScope = ValidatorScope()
block(validatorScope, value)
val otherwises: List =
validatorScope.validatables.mapNotNull { if (it.predicate()) it.otherwise() else null }
if (otherwises.isEmpty()) return Either.Right(value)
val sanitizedOtherwises: List = buildList {
addAll(otherwises)
if (otherwises.count { it.contains(InvalidProperty) } > 1) {
removeAll { it.contains(InvalidProperty) }
add(MultipleInvalidProperties)
}
if (otherwises.count { it.contains(EmptyProperty) } > 1) {
removeAll { it.contains(EmptyProperty) }
add(MultipleEmptyProperties)
}
}
val title = "'$name' is invalid due to:\n"
val otherwisesAsText: String =
sanitizedOtherwises.joinToString("\n") { message -> " - $message" }
val errorMessage: String = title + otherwisesAsText
return Either.Left(value = errorMessage)
}
public companion object {
public inline operator fun invoke(
name: String = T::class.simpleName ?: "Validator",
@UseContextParameters noinline block: ValidatorScope.(T) -> Unit,
): Lazy> = lazy { Validator(name = name, block = block) }
}
}
@PublishedApi internal const val InvalidProperty: String = "Invalid property"
@PublishedApi internal const val MultipleInvalidProperties: String = "Multiple invalid properties"
@PublishedApi internal const val EmptyProperty: String = "Empty property"
@PublishedApi internal const val MultipleEmptyProperties: String = "Multiple empty properties"
© 2015 - 2025 Weber Informatics LLC | Privacy Policy