StringResResolver.kt 1.76 KB
Newer Older
1 2
@file:Suppress("unused")

3 4 5 6 7
package fr.chenry.android.freshrss.utils

import android.content.Context
import androidx.annotation.StringRes

8 9
interface IResourceResolver {
    operator fun invoke(context: Context): String
10 11
}

12 13
class FunctionResourceResolver internal constructor (private val cb: Context.() -> String): IResourceResolver {
    override operator fun invoke(context: Context): String = cb(context)
14 15
}

16 17
object EmptyStringResourceResolver: IResourceResolver {
    override operator fun invoke(context: Context): String = ""
18 19
}

20
class IdResourceResolver @JvmOverloads internal constructor(
21 22
    @StringRes private val resId: Int,
    vararg args: Any = arrayOf()
23
): IResourceResolver {
24
    private val formatArgs: MutableList<Any> = args.toMutableList()
25 26 27 28 29 30 31 32

    fun add(any: Any) = this@IdResourceResolver.formatArgs.add(any)
    operator fun Any.unaryPlus() = add(this)

    fun addAll(all: Collection<Any>) = this@IdResourceResolver.formatArgs.addAll(all)
    fun addAll(all: Iterable<Any>) = this@IdResourceResolver.formatArgs.addAll(all)
    fun addAll(all: Sequence<Any>) = this@IdResourceResolver.formatArgs.addAll(all)
    fun addAll(vararg all: Any) = this@IdResourceResolver.formatArgs.addAll(all)
33

34
    override operator fun invoke(context: Context): String {
35
        val fargs = formatArgs.map {
36
            if(it is IResourceResolver) it(context) else it
37 38 39 40 41 42
        }

        return if(fargs.isEmpty()) context.getString(resId) else context.getString(resId, *fargs.toTypedArray())
    }
}

43
fun emptyStringRes() = EmptyStringResourceResolver
44

45 46
@JvmOverloads
fun idResRes(
47 48
    @StringRes resId: Int,
    vararg args: Any = arrayOf(),
49
    cb: IdResourceResolver.() -> Unit = {}
50
) = IdResourceResolver(resId, *args).apply(cb)
51

52
fun functionRes(cb: Context.() -> String) = FunctionResourceResolver(cb)