All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.ru.astrainteractive.klibs.mikro.validation.impl.ValidationContextImpl.kt Maven / Gradle / Ivy

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)
                    }
                }
            }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy